移动仅包含可移动std :: map的类的构造函数,不起作用

时间:2020-07-04 19:18:57

标签: c++ move-constructor

我有一个包含std::map<int, std::mutex>的类,以某种方式我无法为其定义move构造函数。 std::mutex是不可复制或不可移动的,但是std::map的move构造函数仍然有效,因为它不需要其类型是可复制或不可移动的:

std::map<int, std::mutex> map1;
std::map<int, std::mutex> map2{std::move(map1)}; //this compiles without warnings

但是然后我有一个包含此类映射的类:

class OnlyMovable{
  std::map<int, std::mutex> map;
public:
  OnlyMovable(const OnlyMovable&& om) : map{std::move(om.map)} //somehow requires copy-ctor of mutex
  {}
};

在这里,gcc给了我一个巨大的错误消息,结尾是抱怨std::mutex没有复制构造函数。

那么此类的move-constructor在哪里调用std :: mutex的copy-constructor,那又如何避免呢?

PS:我知道这门课没有意义,只是从我的实际课中得到的一个简单的可验证示例。

1 个答案:

答案 0 :(得分:3)

您假定的move构造函数采用const右值引用。 om无法修改,这意味着其成员无法移出。只需放下const