首页 > 编程语言 > 详细

C++中 shared_ptr的拷贝和赋值——引用计数理解

时间:2020-07-28 22:21:31      阅读:440      评论:0      收藏:0      [点我收藏+]

  当进行拷贝或赋值操作时,每个shared_ptr都会纪录有多少个其他shared_ptr指向相同的对象:

  auto p = make_shared<int>(50);//p指向的对象只有p一个引用者
  auto q = p; //p和q指向相同对象,此对象有两个引用者;

  智能指针类能记录有多少个shared_ptr指向相同的对象,并能在恰当的时候自动释放对象!

 

  关于shared_ptr的引用计数测试demo:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;
int main()
{
    vector<shared_ptr<int>> intPtr;
    vector<shared_ptr<int>> intPtr2;
    for (int i = 0; i < 10; ++i) {
        intPtr.emplace_back(make_shared<int>(i));
    }
    for (int i = 0; i < 10; ++i) {
        cout << "intPtr " << i << " = " << *intPtr.at(i) << endl;        
    }

    intPtr2 = intPtr;
    /*
    cout << "2:  intPtr[0].use_count() = " << intPtr[0].use_count() << endl;
    cout << "2:  intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;
    */

    cout << "intPtr[0]  = " << intPtr[0] << endl;
    cout << "intPtr2[0] = " << intPtr2[0] << endl;

    intPtr[0] = make_shared<int>(50);

    cout << "3:  intPtr[0].use_count()  = " << intPtr[0].use_count() << endl;
    cout << "3:  intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;

    cout << "intPtr[0]  = " << intPtr[0] << endl;
    cout << "intPtr2[0] = " << intPtr2[0] << endl;

    cout << "intPtr[0]  = " << *intPtr[0] << endl;
    cout << "intPtr2[0] = " << *intPtr2[0] << endl;


    return 0;
}

 

C++中 shared_ptr的拷贝和赋值——引用计数理解

原文:https://www.cnblogs.com/create-serenditipy/p/13393511.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!