简体   繁体   English

如何统一初始化unique_ptr的映射?

[英]How to uniform initialize map of unique_ptr?

I have this code to initialize map from into to unique_ptr.我有这个代码来初始化映射到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;

   ^

unique_ptr is movable, but not copyable. unique_ptr是可移动的,但不可复制。 initializer_list requires copyable types; initializer_list需要可复制的类型; you can't move something out of an initializer_list .你不能从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.) (这与最少的复制代码一起最有用。)

As a workaround and especially when you want to have a const map containing unique_ptr , you can use a lambda executed in place.作为一种解决方法,尤其是当您想要一个包含unique_ptrconst map ,您可以使用就地执行的lambda It is not an initializer list , but the result is similar:它不是一个初始化列表,但结果是类似的:

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

or even simpler without typedef using make_pair:甚至不用 typedef 使用 make_pair 更简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM