class Wife;
class Husband
{
public:
void setWife(const shared_ptr<Wife>& wife)
{
this->myWife = wife;
cout << "myWife's use_count" << myWife.use_count() << endl;
}
~Husband()
{
cout << "myWife's use_count" << myWife.use_count() << endl;
cout << "Husband is deleted" << endl;
}
private:
shared_ptr<Wife> myWife;
//weak_ptr<Wife> myWife;
};
class Wife
{
public:
void setHusband(const shared_ptr<Husband>& husband)
{
this->myHusband = husband;
cout << "myHusband's use_count" << myHusband.use_count() << endl;
}
~Wife()
{
cout << "myHusband's use_count" << myHusband.use_count() << endl;
cout << "Wife is deleted" << endl;
}
private:
//shared_ptr<Husband> myHusband;
weak_ptr<Husband> myHusband;
};
int main()
{
shared_ptr<Husband> husband(new Husband);
shared_ptr<Wife> wife(new Wife);
husband->setWife(wife);
wife->setHusband(husband);
}
- shared_ptr使用的注意事项:
//1.不能使用一个原始地址初始化多个共享智能指针
struct Test
{
Test(){}
~Test()
{
cout << "class Test is disstruct ..." << endl;
}
};
int main()
{
Test* te = new Test();
shared_ptr<Test> p1(te);
{
shared_ptr<Test> p2(te);
}
//重复释放已经delete的内存,崩溃
return 0;
}
//2 shared_ptr所管理的对象应该来自堆
int main()
{
int x = 12;
shared_ptr<int> ptr(&x);//栈对象,程序崩溃,尽量不要从原指针创建shared_ptr,应该使用make_shared
return 0;
}
//3.函数不能返回管理了this的共享智能指针对象
因为在函数内部使用指向this的智能指针,离开函数后,引用计数为0,this被析构;
使用方法:
#include <boost/enable_shared_from_this.hpp>
class Y: public boost::enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
//4.共享智能指针不能循环引用