Warn if accessing moved object in C++11 [duplicate

2020-03-08 09:26发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
What can I do with a moved-from object?

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
}

At least, gcc 4.7.2 and clang 3.2 with -Wall do not complain.

Update: Looking back at this question, the critical point is that the compiler cannot decide whether an object is still valid after it has been moved from. If the proposal N4034: Destructive Move was accepted, I would expect the compiler to have more options (but only if the move is destructive).

回答1:

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 unspecified 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};

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.