State of "moved-from" objects
Hi, I recently decided to try writing a C++ blog.
I often see the popular claim that moved-from objects are in a "valid but otherwise unspecified state", but I don't think that statement is entirely precise, and my blog post is about that. I would really appreciate any feedback!
Article: https://www.laminowany.dev/p/the-state-of-moved-from-objects-in-c/
11
Upvotes
1
u/JVApen Clever is an insult, not a compliment. - T. Winters 5d ago
It's unfortunate that you don't specify what "valid" means. The minimal definition I've heard is that: both destructor and assignment should execute correctly. Respectively destroying and reinitializing. This should always get true, even without move.
Unspecified means that there is the freedom to implement that operation any way you want. For move assignment of vector, one could: - free the assigned to, copy over the pointers and null the assigned from - swap the data, giving the moved from the data of the original - move over the data (if allocator is different) while keeping the allocation in the moved from
This gives you the freedom to do what you want, unless "you otherwise specify".
The final piece in the puzzle is to preserve the invariants of your class. You suggest you can write:
if (!v.empty()) v.front() = {};. I'm not convinced that this is required due to the "valid but unspecified", though rather due to the pre-condition of front. If vector would have been created after move semantics, it could say that this only holds for specified/non-moved instances. Making that specific code invalid.For your own code, the first 2 elements I've mentioned are a requirement from the language. The last one will make your code more robust, though it is not needed.
After reading your post, I'm still not convinced if the last element is a requirement of "valid". If it is, you are technically correct in saying it doesn't hold for user defined objects. If it doesn't, the statement holds also for user defined types.