【问题标题】:How to uniform initialize map of unique_ptr?如何统一初始化unique_ptr的map?
【发布时间】:2013-06-15 08:44:00
【问题描述】:

我有这段代码将映射从 into 初始化为 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;

   ^

【问题讨论】:

标签: c++ c++11 map smart-pointers uniform-initialization


【解决方案1】:

作为一种解决方法,尤其是当您想要一个包含unique_ptrconst map 时,您可以使用就地执行的lambda。它不是初始化列表,但结果类似:

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

甚至更简单,不用 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;
}());

【讨论】:

    【解决方案2】:

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

    顺便说一句,知道您遇到了哪个特定错误会更有帮助。否则,我们必须猜测您是否做错了什么,或者您想要做的事情是否没有在您的编译器中实现,或者根本不支持该语言。 (这与最少的复制代码一起最有帮助。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-17
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多