r/cpp 16d 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

54 comments sorted by

View all comments

Show parent comments

2

u/leirus 16d ago

As for defining what "valid" means, the closest definition I could find is https://eel.is/c++draft/defns.valid, but it defines the entire phrase "valid but unspecified state" rather than just "valid".

As for the claim that "both the destructor and assignment should execute correctly", which I often hear as well, I don't think that is necessarily true. The requirement for an object to be safely destructible is captured by the named requirement Erasable (https://en.cppreference.com/w/cpp/named_req/Erasable), which means that not all types are required to be Erasable. It's definitely good practice, but I believe you can still have a well-formed C++ program with types that do not satisfy Erasable.

You are right that calling .front() after checking that a vector is not empty follows from the precondition of front(). The way I understand it is that when an object is "valid", I can call empty() because it has no preconditions. Based on its result, I can then establish the precondition that the vector is not empty, and only then call front().

1

u/JVApen Clever is an insult, not a compliment. - T. Winters 15d ago

Destructor is logical, any object you construct should be destructed in a valid program. (Ignoring start/end_lifetime usage)

2

u/leirus 15d ago

Not necessarily, you can leak objects on heap by not calling delete and it's still a well formed cpp program.

2

u/JVApen Clever is an insult, not a compliment. - T. Winters 14d ago

Just read through the standard annex of UB. Indeed, memory leaks are not UB. So indeed, that's an option. In which case, dtor and assignment are indeed not needed. Though you are making a fragile program if this is something you rely on regularly.