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