您的位置:首页 > 编程语言 > C语言/C++

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

2016-07-11 22:44 531 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shared-ptr C++11