以下程序显示了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整洁的bugprone-use-after-move
检查器支持这种诊断:
bugprone-use-after-move
如果对象在移动后被使用,则发出警告,例如:
std::string str = "Hello, world!n"; std::vector<std::string> messages; messages.emplace_back(std::move(str)); std::cout << str;
最后一行将触发一个警告,即str在已移动。
[…]
使用
移动变量的任何非重新初始化的情况(见下文(都被视为使用。
[…]
如果移动后发生多次使用,则只标记其中的第一次。
clang整洁有一个performance-move-const-arg
检查,它会警告:
- 如果用常量参数调用std::move((
- 如果std::move((是用一个普通可复制类型的参数调用的
- 如果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