在C ++ 11中访问移动的对象时发出警告 [英] Warn if accessing moved object in C++11
问题描述
可能重复:
对移动对象可以做什么?
在调用 std :: move
并将结果传递给函数之后,通常必须假定稍后访问移动的对象将会导致在未定义的行为。
After you called std::move
and passed the result to a function, you generally have to assume that accessing the moved object later will result in undefined behavior.
是否有可以检测到这些访问并警告您的工具。例如:
Are there tools that can detect those accesses and warn you. For example:
{
Widget w;
foo(std::move(w));
// w may be undefined at this point
w.doSomething(); // WARN
}
至少 gcc 4.7.2 和
clang 3.2 与
-Wall
不要抱怨。
推荐答案
也不应该。移动类的行为是任何你想要的。这不是编译器应该警告的。
Nor should they. The behavior of a moved-from class is whatever you want it to be. It is not something that a compiler should be warning about.
对于标准库对象,移动类处于有效但未定义的状态。因此,这样做是完全合法的:
For standard library objects, a moved-from class is in a "valid but undefined state". As such, it is perfectly legal to do this:
std::vector<int> v{20, 30, 40};
std::vector<int> v2 = std::move(v);
v = std::vector<int>{50, 60, 70, 80};
清除
向量的状态为;它只是清除向量。因此,它被复位到已知状态。类似地, operator =
不关心当前状态是什么;它会将其重置为已知状态。
clear
doesn't care what the current state of the vector is; it just clears the vector. Thus it is reset to a known state. Similarly, operator=
doesn't care what the current state is; it will reset it to a known state.
这篇关于在C ++ 11中访问移动的对象时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!