How to uniformly initialize a unique_ptr map?

I have this code to initialize a map from to to unique_ptr.

auto a = unique_ptr<A>(new A()); map<int, unique_ptr<A>> m; m[1] = move(a); 

Can uniform initialization be used? I tried

 map<int, unique_ptr<A>> m {{1, unique_ptr<A>(new A())}}; 

But I have a mistake.

Some part of the error message

 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; ^ 
+6
source share
2 answers

unique_ptr is movable but not copyable. initializer_list type required for copy; you cannot move something from initializer_list . Unfortunately, I believe that what you want to do is impossible.

By the way, it would be more useful to know what specific error you received. Otherwise, we must guess whether you did something wrong and what, or what you want to do, is not implemented in your compiler or simply not supported in this language. (This is most useful along with a minimal replay code.)

+7
source

As a workaround, especially if you want to have a const map containing unique_ptr , you can use lambda done in place. This is not a list of initializers , but the result is similar:

 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; }()); 
0
source

Source: https://habr.com/ru/post/947606/


All Articles