Self-exchange leaves us in a valid but unspecified state

7 points by aatango


snej

This article seems misleading. Clearly std::exchange(x,x) is broken and should not be used. You didn’t actually explain what the problem is: in its first line when it moves obj to a temporary, it doesn’t expect that new_value is aliased to obj and is therefore destroyed (left in a moved-from state.) This is either a bug in the implementation, or the spec should spell out that this aliasing is not allowed.

Similar bugs can happen in implementations of operator= for move assignment; one should be careful to handle the special case where an instance is assigned to itself.

Trying to call this a way to clear x is … just silly, really.