4 ms·
Herb Sutter's article shows why this is actually a big problem in practice. He has an example of a class containing a guaranteed-non-null owning pointer. Leavin
by roca 7y ago
Herb Sutter's article shows why this is actually a big problem in practice. He has an example of a class containing a guaranteed-non-null owning pointer. Leaving an object of this class in a "valid but unspecified state" means when you move out of it, you'll have to replace the internal pointer with a pointer to some new allocation, the very thing move semantics is supposed to help avoid. He suggests that such a class should simply not be moveable.
So the fact that moves are not destructive is indeed very limiting.
- AnimalMuppet 7y agoNot quite. Let's suppose that I've got a pointer to a rather large array, and that array can't be null. When I move, the moved-from then has to allocate a new array, to satisfy the can't-be-null constraint. So I have the overhead of the allocation. But I don't have the overhead of copying all the bytes of the array.
- evanpw 7y agoThat workaround is also problematic, because move constructors are supposed to be noexcept, but 'new' can throw std::bad_alloc. So you either have to lie to the compiler and tell it that your move constructor is noexcept (maybe reasonable in this case since a bad allocation will then call std::terminate), or else you have bad consequences like std::vector silently copying your object instead of moving it.
- roca 7y agoSure, but that's almost as bad.
- unlinked_dll 7y ago>So I have the overhead of the allocation. But I don't have the overhead of copying all the bytes of the array. The overhead of allocation is a magnitude greater evil than copying the bytes of the data structure the vast majority of the time. Most data is small and short lived. As well, copying bytes in memory doesn't have side effects and is far more deterministic than allocation. The fact the spec says non trivially-copyable data must be in some "valid but unspecified" state means that move semantics in C++ are borderline useless, except in contrived cases like the one you present.
- AnimalMuppet 7y agoNot quite. It's the "pointer cannot be null" requirement that makes it useless here. If you allow "pointer can be null for a moved-out-of object", then they're much more useful. I'd say that it's the "pointer must not be null, even for a moved-out-of object" that's the "contrived" part.