问题:
int* p = new int;
shared_ptr<int> sp1(p);
shared_ptr<int> sp2(p); //error
上述问题出在sp1和sp2都会在丢失p的拥有权时释放相应资源,也就是会析构两次。
基于此,必须保证对象只被一组shared_ptr拥有,应该总是在创建对象和相应资源时直接设立
smart pinter:
shared_ptr<int> sp1(new int);
shared_ptr<int> sp2(sp1);
问题1可能会在比较隐蔽的地方出现:
shared_ptr<Person> mother(new Person("mother"));
shared_ptr<Person> kid(new Person("kid"));
kid->setMotherAndFather(mother);
class Person
{
public:
...
void setMotherAndFather(shared_ptr<Person> mother)
{
mom =mother;
mom->kids.push_back(shared_ptr<Person>(this));//error
}
shared_ptr<Person> mother;
vector<shared_ptr<Person>> kids;
};
上述问题出在shared_ptr<Person>(this),这里根据this建立起来的shared_ptr使得kid拥有了
另一组share_ptr。对付这种情况可以有两种办法:
1、将kid作为第二参数传过去
2、可以从std::enable_shared_from_this<>派生自己的类,表现出被shared pointer管理的对
象,做法是将类名称当做template实参传入,然后就可以使用一个派生的成员函数
shared_from_this()建立起一个源自this的shared_ptr
class Person : public std::enable_shared_from_this<Person>
{
public:
...
void setMotherAndFather(shared_ptr<Person> mother)
{
mom =mother;
mom->kids.push_back(shared_from_this());//ok
}
shared_ptr<Person> mother;
vector<shared_ptr<Person>> kids;
};
注意:请不要在类构造函数使用shared_from_this(),否则会在运行期报错