Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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."?

like image 211
fredoverflow Avatar asked Feb 26 '12 10:02

fredoverflow


People also ask

Does STD move set pointer to null?

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.

What happens when a pointer is set to null?

Explanation: What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null.

Should pointers be initialized to null?

You are definitely encouraged to set pointers to NULL whenever the alternative is your pointer having an indeterminate value. Usage of pointers with an indeterminate value is undefined behavior, a concept that you might not grasp properly if you're used to C programming and come from higher level languages.

How do you set a pointer to null pointer?

We can directly assign the pointer variable to 0 to make it null pointer.


1 Answers

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.

like image 182
Dietmar Kühl Avatar answered Oct 14 '22 15:10

Dietmar Kühl