首页 > 解决方案 > 是否有关于这种使用 std::move 的编译警告?

问题描述

以下程序显示了std::move(). 是否可以使用 LLVM 获得关于这些的编译警告?我注意到对于其他一些std::move冗余的上下文有诊断。

我用 bcc32c 5.0.2 版(基于 LLVM 5.0.2)编译了它,没有收到任何警告。

#include <vector>

int main() {
    const std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {3, 4, 5};

    std::vector<int> c = std::move(a); // std::move from const

    std::vector<int> d = std::move(b);

    std::vector<int> e = b; // used after std::move
}

标签: c++clangllvmc++builder

解决方案


clang-tidy 有一个performance-move-const-arg检查警告:

  1. 如果使用常量参数调用 std::move(),
  2. 如果 std::move() 使用可简单复制类型的参数调用,
  3. 如果 std::move() 的结果作为 const 引用参数传递。

在所有这三种情况下,检查将建议删除 std::move() 的修复程序。

以下示例:

const string s;
return std::move(s);  // Warning: std::move of the const variable has no effect

int x;
return std::move(x);  // Warning: std::move of the variable of a trivially-copyable type has no effect

void f(const string &s);
string s;
f(std::move(s));      // Warning: passing result of std::move as a const reference argument; no move will actually happen

推荐阅读