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

南笙酒味 提交于 2019-12-30 07:56:55

问题


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.



来源:https://stackoverflow.com/questions/14552690/warn-if-accessing-moved-object-in-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!