是否可以使用对shared_ptr拥有的对象的引用

Is it OK to use reference to the object owned by a shared_ptr?

本文关键字:拥有 对象 引用 ptr 可以使 shared 是否      更新时间:2023-10-16

我发现这运行良好,但不知道这是否安全,因为我不明白它为什么有效:

struct X{
  static X& make(){
    return *std::make_shared<X>();
  }
  ...
}
int main(){
   const auto& a = X::make();
   a.function();
   ...
   // seems like the instance holds and nothing broken
}

在我的理解中,从shared_ptr operator*中返回对 derefed 对象的引用不应影响shared_ptr管理实例引用计数的方式:因此make()中创建的实例应在make()完成后销毁。但是这种代码模式已经运行了很多次,我不明白为什么。所以我不确定我们是否真的能以这种方式做到这一点......感谢任何评论!

不,从 make_shared 返回的共享指针在返回后会立即被销毁,因此通过取消引用它获得的引用将悬而未决。它可能看起来有效,但它实际上只是未定义的行为,并且如注释中所述,未定义是未定义的。