如何统一初始化unique_ptr的map?

12
我有这段代码用于从一个类型到 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;

   ^

发生了什么错误?当你运行程序时它崩溃了吗? - Mooing Duck
可能是重复的问题:为什么我不能将unique_ptr推入vector中? - Nicol Bolas
2个回答

15

unique_ptr是可移动但不可复制的。 initializer_list 需要可复制的类型;你无法从 initializer_list 中移出某些东西。不幸的是,我认为你想做的事情是不可能的。

顺便说一下,知道你收到的具体错误会更有帮助。否则,我们必须猜测你是否做错了什么以及是什么,或者你想要做的事情在你的编译器中没有实现,或者在语言中根本没有支持。(这与最小复制代码一起使用最有帮助)


2
作为解决方法,特别是当您想要拥有包含unique_ptr的const map时,您可以使用一个现场执行的lambda。它不是初始化列表,但结果类似:
typedef std::map<uint32_t, std::unique_ptr<int>> MapType;
auto const mapInstance([]()
{
   MapType m;
   m.insert(MapType::value_type(0x0023, std::make_unique<int>(23)));
   return m;
}());

甚至更简单,不使用typedef,而是使用make_pair函数:

auto const mapInstance([]()
{
   std::map<uint32_t, std::unique_ptr<int>> m;
   m.insert(std::make_pair(0x0023, std::make_unique<int>(23)));
   return m;
}());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接