【发布时间】: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