Possible Duplicate:
What can I do with a moved-from object?
For example, see this code:
template<class T>
void swap(T& a, T& b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
Is it just me, or is there a bug here? If you move a into tmp, then doesn’t a become invalid?
i.e. Shouldn’t the move-assignment to a from b be a move-constructor call with placement new instead?
If not, then what’s the difference between the move constructor and move assignment operator?
template<class T>
void swap(T& a, T& b)
{
T tmp(std::move(a));
new(&a) T(std::move(b));
new(&b) T(std::move(tmp));
}
When you move data out of an object, the intended semantics is that the object that was moved from ends up in an unspecified but valid state. That means that you can’t predict anything about what state the object will be in other than that it will be a well-formed object. This is not quite the same as “this object is dead and gone.” Moving data out of an object doesn’t end the object’s lifetime – it just changes its state to something unspecified – and consequently it’s perfectly safe to assign that object a new value.
As a result, the initial version of the swap function is safe. After moving data from a, that object holds some unspecified “safe but unpredictable” value. This value is then overwritten when move-assigning it the value of b.
That second version is unsafe, because the lifetime of a has not ended before you try to construct a new object on top of it. This leads to undefined behavior.
Hope this helps!