我发现(感谢 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;
}
基本上,如果抛出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!
}
如您所见,返回item
是无效的,因为我不得不移动item
使用std::move
将其放入items
容器中。
我想不出需要将item
' 的地址存储在附加变量中的解决方案。然而,原始(错误)解决方案非常简洁且易于阅读。
有没有更优雅的方式来返回一个std::unique_ptr
被移动以放置在容器中的东西?