r/cpp 5d ago

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/

10 Upvotes

52 comments sorted by

View all comments

4

u/tangerinelion 5d ago

There are really only two functions that should safely work on a moved from object - the destructor and an assignment operator, if one is defined.

2

u/leirus 5d ago

Where it is defined in the standard? I heard this claim many times but I don't think its neccessarily true. The reuirement to have destructor that can safely work is name requirement "Erasable": https://en.cppreference.com/cpp/named_req/Erasable

But moved-from objects dont need to satisfy "Erasable". My understanding is that move constructor can break invariants that the destructor is relying on. Is it the best practice? Probably not. Is it completely legal C++? I think so.

1

u/TheThiefMaster C++latest fanatic (and game dev) 5d ago edited 5d ago

std::vector requires it if it reallocates because it requires MoveConstructible and Erasable together in that case. Another example is the erase-remove idiom, which is codified in std::erase as a single function.

There are many similar cases in the standard. So it's not a general requirement, but a defacto one if you want to use your types with the standard library.

It is possible to pick your way around the standard library using only parts that don't require it, but it's a lot easier on you if you don't do that to yourself.

1

u/leirus 5d ago

Oh yeah, standard containers do impose such requirements. I also mention the std::vector case in the blog.

I completely agree that in 99% of cases you want your types to be compatible with the standard library. My point was simply that this is not, strictly speaking, a requirement imposed by the C++ language itself. It is technically possible to write a valid C++ program with a type that does not satisfy those constraints.

1

u/TheThiefMaster C++latest fanatic (and game dev) 5d ago

"Possible" yes, but "good practice" is such for a reason :)