c++ shared_ptr误区之row pointer被多组shared_ptr拥有

//确保对象直接被一组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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值