如何统一初始化unique_ptr的地图? [英] How to uniform initialize map of unique_ptr?

查看:172
本文介绍了如何统一初始化unique_ptr的地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我可以使用统一初始化这个吗?我试过

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

但是我收到一个错误。



错误信息的某些部分是

 在'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> >]':...在/ opt / local / include / gcc48 / c ++ / memory:81:0中包含的文件中,来自smart_pointer_map.cpp的
:3:/ opt / local / include / gcc48 / c ++ /bits/unique_ptr.h:273:7:error:declaration here
unique_ptr(const unique_ptr&)= delete;

^


解决方案

unique_ptr 是可移动的,但不可复制。 initializer_list 需要可复制类型;您不能从 initializer_list 中移动某些东西。不幸的是,我相信你想做的是不可能的。



顺便提一下,知道你遇到的具体错误会更有帮助。否则,我们必须猜测你是否做错了什么,或者你想要做什么是不是在编译器中实现,或者根本不支持这种语言。 (这是最有用的,最小的复制代码。)


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;

   ^

解决方案

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.)

这篇关于如何统一初始化unique_ptr的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆