c++ - 将 std::unique_ptr 插入 std::set

标签 c++ stl insert unique-ptr stdset

插入 std::unique_ptr 的最佳方式是什么? std::make_unique() 制作 变成 std::set ?两者insert()emplace()工作,但哪一个更好?

最佳答案

unique_ptr 的实现方式(仅移动,不复制)可以防止您担心的这种情况。但创建其他的:

s.insert( std::make_unique<X>(1) ); // SAFE

auto p2 = std::make_unique<X>(2);
s.insert( std::move(p2) ); // also safe

auto p3 = std::make_unique<X>(3); 
//s.insert( p3 ); // unsafe, compiler complains

s.emplace( std::make_unique<X>(4) ); // SAFE
auto p5 = std::make_unique<X>(5);
s.emplace( std::move(p5) ); // also safe

auto p6 = std::make_unique<X>(6);
//s.emplace( p6 );  // unsafe on exception, compiler will complain if you uncomment

auto p7 = std::make_unique<X>(7);
s.emplace( std::move(p7) ); // also safe
s.emplace( std::move(p7) ); // insert same agains also "safe", but inserts "null"
s.emplace( std::move(p2) ); // insert "null" again, but nulls are highlanders here 

https://godbolt.org/z/3Gfoo7

如果您插入或放置它并不重要,它总是通过移动语义发生,即使您 s.insert( std::make_unique<X>(1) ) ,这是一个 Action 。

在此示例中,3 和 6 从未进入集合,即使您将其移动两次(如示例中的最后两行 p7 或 p2 所示),它们在插入/放置在集合中后仍将为“空”。

关于c++ - 将 std::unique_ptr 插入 std::set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959225/

相关文章:

c++ - 使用opencv显示视频

C++ msvcp90d.dll 访问冲突异常

c++ - 表格的STL容器

c++ - 错误#include'ing <unordered_map>

MYSQL 选择少一行

c++ - C++ 中的流使程序崩溃

c++ - 可以将具有 Base 类型的 STL 容器转换为 Derived 类型吗?

c++ - 将 initializer_list 分配给 std::array

php - 使用 1 个表单插入多个订单

MYSQL insert into table with one column's data pulled from another table