shared_ptr智能指针

来自博客:https://www.cnblogs.com/lzpong/p/6188034.html

      多线程程序经常会遇到在某个线程A创建了一个对象,这个对象需要在线程B使用,

在没有shared_ptr时,因为线程A,B结束时间不确定,即在A或B线程先释放这个对象都有可能造成另一个线程崩溃,

所以为了省时间一般都是任由这个内存泄漏发生.

当然也可以经过复杂的设计,由一个监控线程来统一删除,

但这样会增加代码量和复杂度.这下好了,shared_ptr 可以方便的解决问题,因为它是引用计数和线程安全的.

shared_ptr不用手动去释放资源,它会智能地在合适的时候去自动释放。

  原理:当多个shared_ptr管理同一个指针,仅当最后一个shared_ptr析构时,指针才被delete。这是怎么实现的呢?答案是:引用计数(reference counting)。引用计数指的是,所有管理同一个裸指针(raw pointer)的shared_ptr,都共享一个引用计数器,每当一个shared_ptr被赋值(或拷贝构造)给其它shared_ptr时,这个共享的引用计数器就加1,当一个shared_ptr析构或者被用于管理其它裸指针时,这个引用计数器就减1,如果此时发现引用计数器为0,那么说明它是管理这个指针的最后一个shared_ptr了,于是我们释放指针指向的资源

demo:

#include<iostream>
#include<memory>
//g++ shared_ptr.cpp -std=c++11
int main() {
int *p = new int(30);
        std::shared_ptr<int> bptr(p);//初始化方式1
        std::shared_ptr<int> aptr = std::make_shared<int>(20);//初始化方式2
        std::shared_ptr<int> cptr(aptr);//初始化方式3

        std::cout << "aptr.use_count() = " << aptr.use_count() <<" value = "<<*aptr<<std::endl;//use_count 是引用计数器 
        std::cout << "bptr.use_count() = " << bptr.use_count() <<" value = "<<*bptr<<std::endl;
        std::cout << "cptr.use_count() = " << cptr.use_count() <<" value = "<<*cptr<<std::endl;
}

 
原文地址:https://www.cnblogs.com/jly594761082/p/10319843.html