Clang-Tidy:移动构造函数通过调用复制构造函数来初始化类成员

Clang-Tidy: Move constructor initializes class member by calling a copy constructor

本文关键字:构造函数 初始化 成员 复制 移动 Clang-Tidy 调用      更新时间:2023-10-16
class Vtx {
private:
    int indexPoint;
    int radius;
    std::string strName;
public:
    Vtx(const int p_indexPoint, const int p_radius, std::string p_strName)
            : indexPoint(p_indexPoint),
              radius(p_radius),
              strName(std::move(p_strName)) {
        std::cout << "Constructorn";
    }
    Vtx(const Vtx& rhs)
            : indexPoint(rhs.indexPoint),
              radius(rhs.radius),
              strName(rhs.strName) {
        std::cout << "Copy constructorn";
    }
    // (#)
    Vtx(const Vtx&& rhs)
            : indexPoint(rhs.indexPoint),
              radius(rhs.radius),
              strName(rhs.strName) {
        std::cout << "Move constructorn";
    }
    ~Vtx() {
        std::cout << "Destructorn";
    }
};

对于此代码,clang-tidy 给了我以下警告消息。

    移动构造函数
  • 通过调用复制构造函数初始化类成员

我不明白什么时候在移动构造函数中调用复制构造函数。(#) 虽然编译效果很好,但我想删除这个警告。我该怎么解决?

你忘记移动成员(对于内置类型,无论如何移动都是复制的,可以省略(

并且从 const 对象移动通常是一个副本,因此您必须更改为

Vtx(Vtx&& rhs)
            : indexPoint(rhs.indexPoint),
              radius(rhs.radius),
              strName(std::move(rhs.strName)) {
        std::cout << "Move constructorn";
    }

请注意,在您的情况下,除了消息(您可以在专用类中移动该代码以Vtx简化实现 BTW(,默认实现是可以的:

Vtx(Vtx&& rhs) = default;