我有这段代码可以将映射从 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/