Why nullifying a moved object or an rvalue?

Viewed 60

In this answer there is a sample implementation of move constructor of a string object:

    string(string&& that)   // string&& is an rvalue reference to a string
    {
        data = that.data;
        that.data = nullptr;
    }

And also beside this toy example I've seen many places that say

a moved object shall be in a valid but unspecified state.

For example a std::string is usually an empty one after being moved. My question is why bother ourself to change the state of a rvalue? If an rvalue refrence is a hint to the callee that "we no longer need the object, so do whatever you want with it", so why change it and set it to nullptr or make the string empty? We can do nothing with it if the caller has told us I no longer use it.

1 Answers

Consider the destructor of the above class. When it's called with a data that's not nullptr after move, then the old object (the object you moved from) would destroy the buffer of the new object (the object you've moved to). Therefore, you need to somehow signal that the object destructor should not deallocate anything. One way is to erase the data.

There are other ways to signal it. A common pattern is to have a bool flag that's true until moved from (usually mutable bool, so moving from const is possible).

Related