【问题标题】:Move constructor of class containing only movable std::map not working移动仅包含可移动 std::map 的类的构造函数不起作用
【发布时间】:2020-07-04 19:18:57
【问题描述】:

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

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:我知道这个类没有意义,但它只是从我的实际类派生的一个简单的可验证示例。

【问题讨论】:

    标签: c++ move-constructor


    【解决方案1】:

    您假定的移动构造函数采用const 右值引用。 om 不能被修改,这意味着它的成员不能被移动。直接删除const

    【讨论】:

    • 不知道我是从哪里得到这个函数签名的......谢谢。
    猜你喜欢
    • 2014-11-22
    • 2019-12-09
    • 2011-11-25
    • 2015-03-16
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2018-02-10
    • 2023-04-08
    相关资源
    最近更新 更多