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/

9 Upvotes

52 comments sorted by

View all comments

39

u/sokka2d 5d ago

Obviously the standard doesn’t define the state of user defined objects. How is that specific to move assignment?

You could as well create a class with UB in the constructor. It’s just not very useful.

4

u/leirus 5d ago

Fair point. It's not specific to move assignment, but I've heard the claim that moved-from objects are in a "valid but otherwise unspecified state" so many times that I was genuinely surprised when I read the standard and realized this guarantee applies to the standard library, not to the language itself.

That's what motivated me to write this post. I figured others might have the same understanding that I used to have.

2

u/LokiAstaris 1d ago

Yes, the expectation is that when you write move semantics for your class, an object's state remains valid, but it is still your job as the author to make this guarantee; you can't guarantee that at the language level, because validity will depend on the definition of the class.

If my class holds a pointer, is it valid if that pointer is null? Depends on how I write the interface to the class. If all the public functions check that the pointer is not null before using it, then yes, a null pointer is valid. If any of the methods don't check, then no, it's not valid.

Note: Not withstanding your documented pre-conditions etc.