码迷,mamicode.com
首页 > 其他好文 > 详细

BOOST Library (1)

时间:2015-05-06 17:11:18      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};

void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";

boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";

sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";

sp2.reset();
std::cout<<"After Reset sp2.\n";
}

 

程序输出内容:
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.

归纳如下:
Shared_pt可以共享内存,两个Shared_ptr之间直接用“=”赋值,每个Shared_ptr内部都有一个计数器记录该内存地址有多少个Shared_ptr持有,可以用use_count()访问。当该计数器为0时,会自动调用delete删除内存。

BOOST Library (1)

标签:

原文地址:http://www.cnblogs.com/jast/p/4482420.html

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