这种代码理论上会有双重自由,但为什么没有重复

This code are theoretically there will be a double free, but why no repetition

本文关键字:为什么 自由 代码 理论上      更新时间:2023-10-16

新Widget由两个智能指针管理器组成,这样就不会出现双自由的问题,但执行后不会出现

std::vector<std::shared_ptr<Widget>> processedWidget;
class Widget {
 public:
  void process();
};
void Widget::process()  {
  processedWidget.emplace_back(this); 
}
int main() {
 {
   std::shared_ptr<Widget> w(new Widget);
   w->process();
 }
  return 0;
}

双重删除是标准中未定义的行为。因此,它可能看起来工作,而隐藏一个灾难。这样的代码的正确方法是使用std::enable_shared_from_this

std::vector<std::shared_ptr<Widget>> processedWidget;
class Widget : private std::enable_shared_from_this<Widget> {
 public:
  void process();
};
void Widget::process()  {
  processedWidget.emplace_back(shared_from_this()); 
}
int main() {
 {
   std::shared_ptr<Widget> w(new Widget);
   w->process();
 }
  return 0;
}