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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值