Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c++ - How to uniform initialize map of unique_ptr?

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

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

Can I use uniform initialize this? I tried

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

But I got an error.

Some part of error message is

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;

   ^
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

unique_ptr is movable, but not copyable. initializer_list requires copyable types; you can't move something out of an initializer_list. Unfortunately, I believe what you want to do isn't possible.

Incidentally, it would be more helpful to know which specific error you got. Otherwise, we have to guess whether you did something wrong and what, or whether what you want to do isn't implemented in your compiler, or is simply not supported in the language. (This is most helpful along with minimal reproduction code.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...