2013-06-18 88 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; 
}());