2013-06-18 19 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

可能な複製はなぜ\ _backをユニークな\ _ptrにベクトル化できないのですか?](http://stackoverflow.com/questions/3283778/why-can-i-not-push-back-a-unique- ptr-into-a-vector) –

答えて

7

unique_ptrでは、可動が、コピー可能ではありません。 initializer_listにはコピー可能なタイプが必要です。 initializer_listから何かを移動することはできません。残念ながら、私はあなたがしたいことは不可能だと信じています。

ちなみに、特定のエラーが発生したことを知っていると便利です。さもなければ、何かが間違っていたかどうか、あるいは何をしたいかがあなたのコンパイラに実装されていないのか、単に言語でサポートされていないのかを推測する必要があります。

0

const mapunique_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; 
}()); 
関連する問題