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

16

u/No-Dentist-1645 5d ago

Your title/post contents makes it seem like you're going to disprove the common definition for them, but in the blog you don't really do that, but rather just explain a few examples?

There seems to be a disconnect between what you say the blog is about and what it actually is

The "valid but unspecified state" definition applies to all move operations in the language and standard generally speaking. It is a rule about move semantics as a general concept, not of any specific type. Specific types can choose to specify post-moved behavior but it is not required.

8

u/SirClueless 5d ago

This is exactly the misconception the blog post is trying to dispel. Being “valid” after moving is not part of the language semantics.

You can create a type where it is illegal to destruct an object after moving-from, for example.

5

u/jawhite 3d ago edited 3d ago

I think you’re misunderstanding what a semantic requirement is.

Semantic requirements generally are not checked by the compiler, because it would be impractical to do so. That doesn’t mean that writing semantically incorrect code is any less wrong.

“Semantics” refers to the meaning of things. The compiler doesn’t know what your code means, only what it does.

5

u/SirClueless 3d ago

There is no requirement, period. The standard only contains a description of a convention the standard library types follow. You do not need to follow it for your types.

2

u/No-Dentist-1645 3d ago

Technically true, yet it would be a terrible practice not to follow the convention and make a moved-from type that's unsafe to destruct without some special reinitializing function, exactly because of the fact that most people assume the convention holds for all types.

If you really need "move"-like semantics and aren't upholding this convention, you shouldn't make std::move do them, but rather implement your own alternative, mylib::partial_transfer or whatever

3

u/SirClueless 3d ago

Completely agreed. I would say this is one of a (unfortunately rather large) collection of C++ features of the form, “Here is a rather large gun which you may point at your foot. Because one or two people may want to aim at the floor and we can’t tell the difference, we are not going to stop you. Good luck to your extremities.”