c++ - 添加要映射的对象的唯一指针

标签 c++ compiler-errors stl unique-ptr

我正在尝试添加唯一的 map 指针。

auto monkey= std::unique_ptr<Animal> (new Animal(1,"Tom"));

std::map<int, std::unique_ptr<const Animal>> animals;    //Map of animals

animals.insert(pair<int, unique_ptr<Animal>>(1,monkey));    // Error here


Error:error: no matching function for call to 'std::pair<int, std::unique_ptr<Animal> >::pair(int&, std::unique_ptr<Animal>&)'

添加它的方式是什么?

最佳答案

std::unique_ptr不可复制,但可以移动,您必须对其进行std::move

您可以这样做:

animals.emplace(1, std::move(monkey));

关于c++ - 添加要映射的对象的唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59680006/

相关文章:

c++ - boost program_options : using zero-parameter options multiple times?

c++ - 使用异步添加二叉树成员编译失败

c++ - switch 语句中的 C2196 错误

c++ - 带空字符的 STL basic_string 长度

c++ - std::map 是一个好的解决方案吗?

c++ - 不破坏上下文的常见 OpenGL 清理操作

c++ - 在模板类中使用 vector 迭代器

c# - 如何使用XmlReader以int形式获取属性值?

visual-c++ - Visual Studio 2008 错误 C2371 : 'int8_t' : redefinition; different basic types (http_parser. h)

c++ - 将 std::find_if 与 std::string 一起使用