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

来源:互联网 发布:ubuntu下如何挂载u盘 编辑:程序博客网 时间:2024/06/05 00:17
#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;}
0 0
原创粉丝点击