是否有关于 std::move 的这种使用的编译警告?

Is there a compile warning about this use of 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
}

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

  1. if std::move() is called with a constant argument,
  2. if std::move() is called with an argument of a trivially-copyable type,
  3. if the result of std::move() is passed as a const reference argument.

In all three cases, the check will suggest a fix that removes the 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

clang-tidy 的 bugprone-use-after-move 检查器支持这种诊断:

bugprone-use-after-move

Warns if an object is used after it has been moved, for example:

std::string str = "Hello, world!\n";
std::vector<std::string> messages;
messages.emplace_back(std::move(str));
std::cout << str;

The last line will trigger a warning that str is used after it has been moved.

[...]

Use

Any occurrence of the moved variable that is not a reinitialization (see below) is considered to be a use.

[...]

If multiple uses occur after a move, only the first of these is flagged.