您的位置:首页 > 编程语言 > C语言/C++

c++ shared_ptr的错误用法之cycle引用

2017-05-13 12:16 239 查看
#include <iostream>
#include <memory>
#include <string>
#include <vector>

using namespace std;

class Person
{
public:
string name;
shared_ptr<Person> monther;
shared_ptr<Person> father;
vector<shared_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()
{
cout << "delete " << name << endl;
system("pause");
}
};
shared_ptr<Person> initFamily(const string& name)
{
shared_ptr<Person> mom(new Person(name + "'s monther"));
shared_ptr<Person> dad(new Person(name + "'s father"));
shared_ptr<Person> kid(new Person(name, mom, dad));
mom->kids.push_back(kid);//++use_count;
dad->kids.push_back(kid);//++use_count;
return kid; //++use_count;
}//--use_count;
int main()
{
shared_ptr<Person> kid = initFamily("Marco");//++use_count;
cout << kid.use_count() << endl;
//因shared_ptr形成cycle无法释放,故无法调用析构函数
//下面的system("pause")则必须有,否则会一闪而过
system("pause");
return 0;
}


//解决办法:使用weak_ptr

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

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()
{
cout << "detele " << name << endl;
}
};
shared_ptr<Person> initFamily(const string& name)
{
shared_ptr<Person> mom(new Person(name + "'s monther"));
shared_ptr<Person> dad(new Person(name + "'s father"));
shared_ptr<Person> kid(new Person(name, mom, dad));
weak_ptr<Person> w_kid(kid);
mom->kids.push_back(w_kid);
dad->kids.push_back(w_kid);
return kid;
}
int main()
{
shared_ptr<Person> p = initFamily("Marco");
cout << p.use_count() << endl;
cout << "the kid is " << p->name << endl;
cout << "the kid's monther " << p->monther->name << endl;
cout << "the kid's father " << p->father->name << endl;
for (auto &v : p->monther->kids)
if (!v.expired())
cout << v.lock()->name << endl;
//析构函数会调用,则下面system("pause")不需要添加
//另外通过命令行编译更直观
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息