3 ms·
I get the impression that the question-and-answer section is circling around the issue of the semantic status of a moved-from variable without quite dispatching
by mannykannot 7y ago
I get the impression that the question-and-answer section is circling around the issue of the semantic status of a moved-from variable without quite dispatching it. Is a variable, when it is moved from and thus (if implemented properly) in a valid though unspecified state, not semantically in the same sort of state as a constructed but uninitialized integer, where any bit pattern is valid, but if it happens to be zero and then used as a divisor, will result in a fault?
Is it not the case that one of the main reasons for the language giving us the ability to write an explicit no-argument constuctor is to address this sort of problem on construction: it allows us to put the object in an application- or library-defined state, thus establishing a convention that helps with correct use? And is it not a common idiom, when writing a move constructor for a class that has an explicit no-argument constructor, to leave the moved-from object in the same state as if it were newly constructed without arguments? (e.g. std::mutex, where that state is unlocked.) (Update: another common idiom is to swap source and destination.) These are the some of the conventions that make an explicit move robust.
- mark-r 7y agoC++ is designed to be low overhead. Requiring a moved-from object to take on a newly-constructed state will add overhead that won't be necessary most of the time. If you want to add your own convention you're free to do so, knowing what the downside will be.
- mannykannot 7y agoIndeed, though it should at least go through destruction without undesirable side-effects. In the article, however, Herb Sutter appears to be arguing for something stronger: Q: Does “but unspecified” mean the only safe operation on a moved-from object is to call its destructor? A: No. ... Q: What about objects that aren’t safe to be used normally after being moved from? A: They are buggy...
- mark-r 7y agoSurely he doesn't consider unique_ptr to be buggy, so there must be some subtlety that isn't captured by that statement. Perhaps it's in the definition of "normally" - you can't dereference a moved-from unique_ptr, but you can certainly reassign it to a new pointer and go on to use it from there.
- mannykannot 7y agoI think so, hence my opening sentence. I think it is also fair to say that library-writers generally have less leeway in this matter than application writers, who may know that certain scenarios are not a problem. BTW, I have updated my original post to mention swapping source and destination, another common idiom for satisfying the requirement.