c++标准库(笔记):智能指针(3) -- shared_ptr使用中可能会出现的问题

本文探讨了在C++中使用shared_ptr管理资源时可能遇到的问题,特别是在对象间引用循环时如何避免资源释放冲突。通过实例说明了正确使用shared_ptr的方法,以及如何利用enable_shared_from_this解决对象自我引用的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:
int* p = new int;
shared_ptr<int> sp1(p);
shared_ptr<int> sp2(p); //error
上述问题出在sp1和sp2都会在丢失p的拥有权时释放相应资源,也就是会析构两次。

基于此,必须保证对象只被一组shared_ptr拥有,应该总是在创建对象和相应资源时直接设立
smart pinter:
shared_ptr<int> sp1(new int);
shared_ptr<int> sp2(sp1);

问题1可能会在比较隐蔽的地方出现:

shared_ptr<Person> mother(new Person("mother"));
shared_ptr<Person> kid(new Person("kid"));
kid->setMotherAndFather(mother);
class Person
{
  public:
    ...
  void setMotherAndFather(shared_ptr<Person> mother)
  {
    mom =mother;
    mom->kids.push_back(shared_ptr<Person>(this));//error
  }
  shared_ptr<Person> mother;
  vector<shared_ptr<Person>> kids;
};


上述问题出在shared_ptr<Person>(this),这里根据this建立起来的shared_ptr使得kid拥有了
另一组share_ptr。对付这种情况可以有两种办法:
1、将kid作为第二参数传过去
2、可以从std::enable_shared_from_this<>派生自己的类,表现出被shared pointer管理的对
象,做法是将类名称当做template实参传入,然后就可以使用一个派生的成员函数
shared_from_this()建立起一个源自this的shared_ptr

class Person : public std::enable_shared_from_this<Person>
{
  public:
    ...
  void setMotherAndFather(shared_ptr<Person> mother)
  {
    mom =mother;
    mom->kids.push_back(shared_from_this());//ok
  }
  shared_ptr<Person> mother;
  vector<shared_ptr<Person>> kids;
};


注意:请不要在类构造函数使用shared_from_this(),否则会在运行期报错 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值