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

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

1
2
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;
}
复制代码

 

posted @   时间的风景  阅读(8855)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
点击右上角即可分享
微信分享提示