
Envoyé par
Bjarne Stroustrup, N3201, Moving right along
I think that the original idea was that a moved-from object would never be used again. The canonical example was “return x;” where move would save us from an expensive copy of x followed by the destruction of x. It follows that the moved-from state must be destructible. It was soon decided that in addition, it would help programmers (especially library builders) if it was possible to assign to a moved-from object. However, even that was not obvious to all and attempts to require further guarantees for the moved-from state elicited strong opposition. The consensus seems to be that a moved-from state must be “valid but unspecified” exactly as an object after a throw under the basic guarantee, but that nothing more can be guaranteed (except possibly for some specific type).
The obvious state of a moved-from object is the “empty state.” The snag is that for some types there is no obvious “empty state” (e.g., consider proxies). How would we know if there was an empty state for a type X? Consider default construction. If there is a default constructor, we have an empty state – and by implication – we have an excellent candidate for the moved-from state. Assuming that we equate “establishing the invariant” with “constructing”, the existence of a default constructor ensures that there is a way to establish the invariant without running multiple operations or supplying arguments. Ignoring details, the obvious default move becomes:
1. Move each element
2. Default construct the moved-from object
This observation leads to the idea: Generate a move operation for X only if we can default construct an X. There may be other constraints on generation; in particular, the ones I suggested in N3174. Let’s explore.
Partager