c++ - 如何统一初始化 unique_ptr 的映射?

标签 c++ c++11 dictionary smart-pointers uniform-initialization

我有这段代码可以将映射从 into 初始化为 unique_ptr。

auto a = unique_ptr<A>(new A());
map<int, unique_ptr<A>> m;
m[1] = move(a);

我可以使用统一初始化吗?我试过了

map<int, unique_ptr<A>> m {{1, unique_ptr<A>(new A())}};    

但是我得到了一个错误。

错误信息的一部分是

In instantiation of 'std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = {const std::pair<const int, std::unique_ptr<A, std::default_delete<A> > >&}; _Val = std::pair<const int, std::unique_ptr<A> >]': ... In file included from /opt/local/include/gcc48/c++/memory:81:0,
                 from smart_pointer_map.cpp:3: /opt/local/include/gcc48/c++/bits/unique_ptr.h:273:7: error: declared here
       unique_ptr(const unique_ptr&) = delete;

   ^

最佳答案

unique_ptr 是可移动的,但不可复制。 initializer_list 需要可复制的类型;您不能从 initializer_list 中移出某些内容。不幸的是,我相信你想做的事是不可能的。

顺便说一句,了解您遇到的具体错误会更有帮助。否则,我们不得不猜测你是否做错了什么,或者你想做的事情是否没有在你的编译器中实现,或者根本不被语言支持。 (这与最少的复制代码一起最有用。)

关于c++ - 如何统一初始化 unique_ptr 的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978632/

相关文章:

python dict() 初始化

c++ - CMake:target_include_directories() 找不到头文件

performance - 我的代码中是否有开销使我的线程运行速度变慢[C++]

c++ - 为什么编译器会产生错误?

c++ - 在应用程序中调用 linux 命令行工具

c++ - std::remove_if 是否保证按顺序调用谓词?

c++ - 从 unordered_multiset 读取会导致崩溃

c# - 可查询语言词典和单词搜索功能

c++11 - C11 和 C++11 原子 : acquire-release semantics and memory barriers

java - 具有值列表的映射的现有 Java 实现?