码迷,mamicode.com
首页 > 编程语言 > 详细

关于C++ shared_ptr的拷贝和赋值——引用计数

时间:2020-07-28 22:13:59      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:ios   class   bsp   size   share   cpp   引用计数   mes   自动   

  当进行拷贝或赋值操作时,每个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的拷贝和赋值——引用计数

标签:ios   class   bsp   size   share   cpp   引用计数   mes   自动   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!