智能指针shared_ptr

Shared pointer
Manages the storage of a pointer, providing a limited garbage-collection facility, possibly sharing that management with other objects.

Objects of shared_ptr types have the ability of taking ownership of a pointer and share that ownership: once they take ownership, the group of owners of a pointer become responsible for its deletion when the last one of them releases that ownership.

#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;

class shared
{
private:
	shared_ptr<int> p;
public:
	shared(shared_ptr<int> p_):p(p_) {}
	void print()
	{
		cout<<"count: "<<p.use_count()<<endl;
		cout<<"v= "<<*p<<endl;
	}
};

void print_func(shared_ptr<int> p)
{
	cout<<"count: "<<p.use_count()<<endl;
	cout<<"v= "<<*p<<endl;
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	shared_ptr<int> p(new int(100));
	shared s1(p),s2(p);
	s1.print();
	s2.print();
	*p=20;
	print_func(p);
	s1.print();
	return 0; //a.exec();
}
/*---------------
count: 3
v= 100
count: 3
v= 100
count: 4
v= 20
count: 3
v= 20
请按任意键继续. . .
--------------------*/

以上示例第三次计数为4,函数调用结束后,局部变量被销毁,计数重新变成3,我想如果用引用传递参数的话,计数应该都是3.

shared_ptr应用于标准容器示例:

int main()    
{        
	typedef vector<shared_ptr<int> > vs;    //一个持有shared_ptr的标准容器类型        
	vs v(10);                               //声明一个拥有10个元素的容器,元素被初始化为空指针         
	int i = 0;        
	for (vs::iterator pos = v.begin(); pos != v.end(); ++pos)        
	{            
		(*pos) = make_shared<int>(++i);     //使用工厂函数赋值            
		cout << *(*pos) << ", ";            //输出值        
	}        
	cout << endl;         
	shared_ptr<int> p = v[9];        
	*p = 100;        
	cout << *v[9] << endl;    
}  

例子转自: http://blog.csdn.net/sndaxdrs/article/details/6175701


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值