2013-06-18 89 views
6

我有这个代码来初始化映射到unique_ptr。如何统一初始化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; 

^
+0

是什么错误?当你运行它时程序崩溃了吗? –

+0

可能的重复[为什么我不能将\ __返回一个唯一\ _ptr成矢量?](http://stackoverflow.com/questions/3283778/why-can-i-not-push-back-a-unique- PTR-成-A-矢量) –

回答

7

unique_ptr是可移动的,但不可拷贝。 initializer_list需要可复制的类型;你不能移动一个initializer_list。不幸的是,我相信你想做的事是不可能的。

顺便说一句,它会更有助于知道你得到了哪个具体的错误。否则,我们必须猜测你是否做错了什么,或者你想要做什么没有在编译器中实现,或者在语言中不支持。 (这是最小再现代码一起最有帮助。)

0

作为一种变通方法,尤其是当你想有一个const map包含unique_ptr,你可以使用一个lambda在地方执行。这不是一个初始化列表,但结果是相似的:

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