从函数返回shared_ptr的解除引用值

Rec*_*ker 3 c++ boost shared-ptr c++11

这是一个菜鸟问题.以下代码是否安全?

boost::unordered_set<std::string> func()
{
      boost::shared_ptr<boost::unordered_set<std::string>> list =
              boost::make_shared<boost::unordered_set<std::string>>();

      /* Code to populate the shared_ptr to unordered_set goes here and I do
         populate my set. */

      return *list;
}
Run Code Online (Sandbox Code Playgroud)

首先会发生什么?shared_ptr通过导致内存故障复制/ NRVO /移动或破坏?如果不安全,我的替代方案是什么?

eer*_*ika 8

有时候是这样的:

  • 制作指向对象的临时副本.这是函数的返回值.副本不能被删除.
  • 函数的局部变量(包括共享指针)将被销毁.
  • 销毁共享指针时,会减少引用计数.如果在函数中没有创建共享指针的副本,则refocount将达到0并且指向的对象将被销毁.

它是安全的,但动态分配和共享指针的使用似乎毫无意义,如果集合很大,副本的低效率可能会损害性能.


既然你没有证明需要使用指针,我建议一个更简单的选择:

boost::unordered_set<std::string> list;

/* Code to populate the unordered_set goes here and I do
     populate my set. */

return list;
Run Code Online (Sandbox Code Playgroud)

NRVO可以应用于此,如果不应用,则通过移动构造返回值.