小编Sha*_*Cao的帖子

可以使用对shared_ptr拥有的对象的引用吗?

我发现这个方法运作良好,但不知道这个方法是否安全,因为我不知道为什么会这样:

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
}
Run Code Online (Sandbox Code Playgroud)

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

c++ reference shared-ptr c++11 c++14

2
推荐指数
1
解决办法
96
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

reference ×1

shared-ptr ×1