Could you give me an example of how to implement a move assignment operator whose class has a destructor that has side effects (like releasing a lock)?
So in a sense, we have drifted into the netherworld of non-deterministic destruction here: a variable has been assigned to, but the object formerly held by that variable is still out there somewhere. That's fine as long as the destruction of that object does not have any side effects that are visible to the outside world. But sometimes destructors do have such side effects. An example would be the release of a lock inside a destructor. Therefore, any part of an object's destruction that has side effects should be performed explicitly in the rvalue reference overload of the copy assignment operator:
X& X::operator=(X&& rhs)
{
// Perform a cleanup that takes care of at least those parts of the
// destructor that have side effects. Be sure to leave the object
// in a destructible and assignable state.
// Move semantics: exchange content between this and rhs
return *this;
}
In this example of a class holding a lock to release on destruction, do we want to release the lock in the assignment operator before exchanging content between this and rhs?
At least doing that we are deterministic about when the lock is released....
I got it. In the sample where an instance of X has a lock to be released upon its destruction, then this lock should be released in the rvalue reference assingment operator, something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
X& X::operator=(X&& rhs)
{
// Perform a cleanup that takes care of at least those parts of the
// destructor that have side effects. Be sure to leave the object
// in a destructible and assignable state
this->unlock();
// Move semantics: exchange content between this and rhs
return *this;
}
Is this correct? Is this what is meant by the text?