C++11 智能指针之 std::shared_ptr 初级学习

shared_ptr概念

  • shared_ptr基于“引用计数”模型实现,多个shared_ptr可指向同一个动态对象,并维护了一个共享的引用计数器,记录了引用同一对象的shared_ptr实例的数量。当最后一个指向动态对象的shared_ptr销毁时,会自动销毁其所指对象(通过delete操作符)。

  • shared_ptr的默认能力是管理动态内存,但支持自定义的Deleter以实现个性化的资源释放动作。

shared_ptr的创建

  • std:make_shared 方式
std:shared_ptr<std:string> a = std:make_shared<std:string>("hello");
  • 构造函数方式
std:shared_ptr<std:string> a(new std:string("hello"));

简单测试代码

#include <iostream>
#include <memory>

using namespace std;

class A{
private:
    int x;
public:
    A(int x):x(x){}
    void print()
    {
        cout<<"x="<<x<<endl;
    }
    ~A()
    {
        cout<<"x="<<x<<" deleted"<<endl;
    }
};

class B
{
public:
    void testB(shared_ptr<A> a)
    {
        cout<<"fourth count="<<a.use_count()<<endl;
        a->print();
    }
};

void testA(shared_ptr<A> a)
{
    cout<<"testA count="<<a.use_count()<<endl;
    a->print();
}

shared_ptr<A> testC()
{
    shared_ptr<A> a = make_shared<A>(2);
    return a;
}

void testD(shared_ptr<A> &a)
{
    cout<<"testD count="<<a.use_count()<<endl;
    a->print();
}

int main()
{
    shared_ptr<A> a(new A(1));
    {
        a->print();
        cout<<"first count="<<a.use_count()<<endl;
        shared_ptr<A> aa = a;
        cout<<"second count="<<a.use_count()<<endl;
        cout<<"second count="<<aa.use_count()<<endl;
        testA(a);
        cout<<"after testA count="<<a.use_count()<<endl;
        B c;
        c.testB(a);
    }
    cout<<"first over count="<<a.use_count()<<endl;

    shared_ptr<A> b = testC();
    cout<<"after testC count="<<b.use_count()<<endl;
    testD(b);
    return 0;
}

输出结果
这里写图片描述

可以看到shared_ptr作为形参的时候(testA和testB)use_count会增加1,但退出函数后回到原来的use_count,但作为引用传递的时候(testD)并不会增加use_count

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值