Warm tip: This article is reproduced from stackoverflow.com, please click
c++ c++11 pointers null move-semantics

Why does moving a pointer variable not set it to null?

发布于 2020-03-27 10:25:28

When implementing move constructors and move assignment operators, one often writes code like this:

p = other.p;
other.p = 0;

The implicitly defined move operations would be implemented with code like this:

p = std::move(other.p);

Which would be wrong, because moving a pointer variable does not set it to null. Why is that? Are there any cases were we would like the move operations to leave the original pointer variable unchanged?

Note: By "moving", I do not just mean the subexpression std::move(other.p), I mean the whole expression p = std::move(other.p). So, why is there no special language rule that says "If the right hand side of an assignment is a pointer xvalue, it is set to null after the assignment has taken place."?

Questioner
fredoverflow
Viewed
50
7,415 2015-07-18 03:19

Setting a raw pointer to null after moving it implies that the pointer represents ownership. However, lots of pointers are used to represent relationships. Moreover, for a long time it is recommended that ownership relations are represented differently than using a raw pointer. For example, the ownership relation you are referring to is represented by std::unique_ptr<T>. If you want the implicitly generated move operations take care of your ownership all you need to do is to use members which actually represent (and implement) the desired ownership behavior.

Also, the behavior of the generated move operations is consistent with what was done with the copy operations: they also don't make any ownership assumptions and don't do e.g. a deep copy if a pointer is copied. If you want this to happen you also need to create a suitable class encoding the relevant semantics.