高效优雅地返回emplaced unique_ptr

Vit*_*meo 4 c++ return unique-ptr c++11 emplace

我发现(感谢StackOverflow注释)我的代码中存在安全漏洞:

std::vector<std::unique_ptr<Item>> items;

template<class... TS> Item& create(TS&&... mArgs)
{
    auto item(new Item(std::forward<TS>(mArgs)...);
    items.emplace_back(item); // Possible exception and memory leak
    return *item;
}
Run Code Online (Sandbox Code Playgroud)

基本上,如果抛出Item,使用raw 分配new可能会泄漏内存emplace_back.

解决方案永远不会使用raw new,而是std::unique_ptr在方法体中使用right.

std::vector<std::unique_ptr<Item>> items;

template<class... TS> Item& create(TS&&... mArgs)
{
    auto item(std::make_unique<Item>(std::forward<TS>(mArgs)...);
    items.emplace_back(std::move(item));
    return *item; // `item` was moved, this is invalid!
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,返回item是无效的,因为我不得不item使用std::move它来将它放入items容器中.

我想不出一个需要item在另一个变量中存储地址的解决方案.然而,原始(错误)解决方案非常简洁易读.

是否有更优雅的方式返回std::unique_ptr被移动到容器中的位置?

Jar*_*d42 8

你可以写:

template<class... TS>
Item& create(TS&&... mArgs)
{
    items.emplace_back(std::make_unique<Item>(std::forward<TS>(mArgs)...));
    return *items.back();
}
Run Code Online (Sandbox Code Playgroud)