【问题标题】:Using operator[] to access a private std::map of unique_ptr使用 operator[] 访问 unique_ptr 的私有 std::map
【发布时间】:2018-01-28 12:55:11
【问题描述】:

我有一个带有 unique_ptr 私有 std::map 的类:

class MyClass{
std::map <KeyType, std::unique_ptr<my_type>> my_map;
...
};

我选择了 unique_ptr,因为 my_map 是 my_type 对象的唯一所有者。

我想公开一个 operator[] 公共成员函数来访问(完美转发)my_map。 比如:

// my_class is of type MyClass
auto ptr = my_type_factory(...); // my_type_factory returns a std::unique_ptr<my_type>
....
my_class[1] = std::move(auto_ptr);

我尝试过各种可能的 operator[] 定义:

class MyClass{
....
public:
auto operator[](KeyType && key) { return my_map[std::forward<KeyType>(key)]; } 
// or return & my_map[...];
};

但它不起作用,最后我总是调用unique_ptr的已删除复制构造函数。

只是为了继续前进,如果我将 my_map 移动到公共接口,我已经通过了所有测试,但这当然是作弊,因为我正在尝试改进我的现代 C++ 技能,并且我认为我有一些原则还没有了解 unique_ptr 和 move。

所以我的问题是:如何在私有 std::map 中使用 std::unique_ptr?

【问题讨论】:

  • @LogicStuff:不能被那个人欺骗,只是被标题所欺骗。

标签: c++ c++11 unique-ptr stdmap


【解决方案1】:

你应该返回一个参考。

auto & operator[](KeyType && key) { return my_map[std::forward<KeyType>(key)]; } 

【讨论】:

  • 但这不会也影响到 unique_ptr 的已删除默认 ctor 吗?
  • @einpoklum unique_ptr 的默认构造函数没有被删除,只有复制构造函数和复制赋值运算符被删除。它将使用 nullptr 初始化。
  • 这很好用。能否请您详细说明,以便我更好地理解?在我的想法中,在 my_map 上调用的 operator[] 已经返回了一个引用,我希望“auto”已经是一个引用。我错过了什么?
  • @Francesco auto 类型推导规则会删除一个引用并产生std::unique_ptr&lt;my_type&gt;,它是decltype(auto) 会产生与您预期完全相同的引用类型。我想这是相当反直觉的。
  • @Francesco 我的意思是decltype(auto) operator[](。已经有几个围绕 SO 提出的问题。
猜你喜欢
  • 2022-08-24
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多