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 /移动或破坏?如果不安全,我的替代方案是什么?
有时候是这样的:
它是安全的,但动态分配和共享指针的使用似乎毫无意义,如果集合很大,副本的低效率可能会损害性能.
既然你没有证明需要使用指针,我建议一个更简单的选择:
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可以应用于此,如果不应用,则通过移动构造返回值.