zoukankan      html  css  js  c++  java
  • C++智能指针shared_ptr

    shared_ptr
    这里有一个你在标准库中找不到的—引用数智能指针。大部分人都应当有过使用智能指针的经历,并且已经有很多关于引用数的文章。最重要的一个细节是引用数是如何被执行的—插入,意思是说你将引用计数的功能添加给类,或者是非插入,意思是说你不这样做。Boost shared_ptr是非插入类型的,这个实现使用一个从堆中分配来的引用计数器。关于提供参数化策略使得对任何情况都极为适合的讨论很多了,但是最终讨论的结果是决定反对聚焦于可用性。可是不要指望讨论的结果能够结束。
    shared_ptr完成了你所希望的工作:他负责在不使用实例时删除由它指向的对象(pointee),并且它可以自由的共享它指向的对象(pointee)。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    void PrintIfString?(constany&Any){
    if(cons tshared_ptr* s=
    any_cast>(&Any)){
    cout<<**s<<endl;
    }
    }
    int main(int argc,char* argv[])
    {
    std::vectorStuff;
    shared_ptrSharedString1?
    (new string("Shareme.Bytheway,Boost.anyisanotherusefulBoostlibrary"));
    shared_ptrSharedString2?
    (SharedString1?);
    shared_ptrSharedInt1?
    (newint(42));
    shared_ptrSharedInt2?
    (SharedInt1?);
    Stuff.push_back(SharedString1?);
    Stuff.push_back(SharedString2?);
    Stuff.push_back(SharedInt1?);
    Stuff.push_back(SharedInt2?);
    //Printthestrings
    for_each(Stuff.begin(),Stuff.end(),
    PrintIfString?);
    Stuff.clear();
    //Thepointeesoftheshared_ptr's
    //willbereleasedonleavingscope
    //shared_ptr的pointee离开这个范围后将被释放
    return0;
    }

    什么叫智能指针?智能指针介绍

    智能指针(smart pointer)是存储指向动态分配(堆)对象指针的类,用于生存期控制,能够确保自动正确的销毁动态分配的对象,防止内存泄露。它的一种通用实现技术是使用引用..

    智能指针shared_ptr的用法

    C++11提供了三种智能指针:std::shared_ptr, std::unique_ptr, std::weak_ptr,使用时需添加头文件<memory>。

    shared_ptr使用引用计数,每一个shared_ptr的拷贝都指向相同的内存。每使用他一次,内部的引用计数加1,每析构一次,内部的引用计数减1,减为0时,删除所指向的堆内存。shared_ptr内部的引用计数是安全的,但是对象的读取需要加锁。

    http://www.cnblogs.com/jiayayao/archive/2016/12/03/6128877.html

  • 相关阅读:
    nginx.conf配置
    分组查询最近时间的记录
    jQuery中$(function(){})与(function($){})(jQuery)、$(document).ready(function(){})等的区别详细讲解
    form表单的onsubmit()问题 集合
    vs代码快捷键
    localStorage存储方法
    display和visibility的区别
    Javascript Math ceil()、floor()、round()三个函数的区别
    sqlservere小计合计总计
    CentOS 7.1 图形化安装
  • 原文地址:https://www.cnblogs.com/2008nmj/p/7064107.html
Copyright © 2011-2022 走看看