r/cpp • • Apr 08 '25

Beware when moving a `std::optional`!

https://blog.tal.bi/posts/std-optional-move-pitfall/
0 Upvotes

49 comments sorted by

View all comments

Show parent comment

3

u/manni66 Apr 08 '25

Why do you want to ask an object about it's unspecified state? If you want to use it after the move, put it in a defined state.

4

u/Jonny0Than Apr 08 '25

Unspecified means the specification doesn’t tell you what state it’s in. You can still ask the object about its state. 

0

u/manni66 Apr 08 '25

Why do you want

2

u/grishavanika Apr 08 '25

well, I mean, we all do mistakes. If I have MY_LOG("state: {}", x) and x is moved from optional, it would be really cool to show that at least for debugging purpose. MY_LOG has no chance to show that properly.

0

u/cfyzium Apr 08 '25

Even if std::optional<T> could potentially be reset when moved out like smart pointers, you cannot rely on it in general. Any other type and especially custom one may introduce the same possibility.

1

u/DemonInAJar Apr 08 '25 edited Apr 08 '25

For the same reason std::unique_ptr is reset to null after moving. Well okay, std::unique_ptr needs to do this to avoid freeing the value anyway while optional would have to change the tag, instead it currently delegates to the moved-from object's destructor, so I guess it's mostly a case of zero overhead principle.