//确保对象直接被一组shared_ptr拥有
//而不是多组直接拥有
#include <iostream>
#include <memory>
using namespace std;
int main()
{
int *p = new int(5);
shared_ptr<int> sp(p);//第一组
shared_ptr<int> sp2(p);//第二组
cout << *sp << ends << *sp2 << endl;
cout << sp.use_count() << ends << sp2.use_count() << endl;
//因为是在调用sp析构函数时出错故这里注释掉
//system("pause");
return 0;
}
//更复杂隐晦的错误
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
//不知不觉使两组shared_ptr拥有同一个row pointer
class Person
{
public:
string name;
shared_ptr<Person> monther;
shared_ptr<Person> father;
vector<weak_ptr<Person>> kids;
public:
Person(const string& n,shared_ptr<Person> m = nullptr,shared_ptr<Person> f = nullptr):name(n),monther(m),father(f)
{}
~Person(){}
void setParentsAndTheirKids(shared_ptr<Person> m = nullptr, shared_ptr<Person> f = nullptr)
{
monther = m;
father = f;
if (m != nullptr)
m->kids.push_back(shared_ptr<Person>(this));//将row pointer交给第一组
if (f != nullptr)
f->kids.push_back(shared_ptr<Person>(this));//将row pointer交给第二组
}
};
int main()
{
system("pause");
return 0;
}
//解决办法
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
//不能在构造函数里使用shared_from_this()因为enable_shared_form_this<Person>
//需要完整的Person来保存shared_ptr
class Person : public enable_shared_from_this<Person>
{
public:
string name;
shared_ptr<Person> monther;
shared_ptr<Person> father;
vector<weak_ptr<Person>> kids;
public:
Person(const string& n,shared_ptr<Person> m = nullptr,shared_ptr<Person> f = nullptr):name(n),monther(m),father(f)
{}
~Person() {}
void setParentsAndTheirKids(shared_ptr<Person> m = nullptr,shared_ptr<Person> f = nullptr)
{
monther = m;
father = f;
if (m != nullptr)
{
m->kids.push_back(shared_from_this());
}
if (f != nullptr)
{
f->kids.push_back(shared_from_this());
}
}
};
int main()
{
system("pause");
return 0;
}