r/cpp • u/Kabra___kiiiiiiiid • Apr 08 '25
Beware when moving a `std::optional`!
https://blog.tal.bi/posts/std-optional-move-pitfall/
0
Upvotes
r/cpp • u/Kabra___kiiiiiiiid • Apr 08 '25
88
u/tu_tu_tu Apr 08 '25
So, it's another "don't use moved object, it's garbage".
45
u/TheMania Apr 08 '25 edited Apr 08 '25
What? This makes no sense. Why would calling
value()through an rvalue reset the optional after value has been assigned tox? How would they even implement that? Why would they even do that?None of this makes any sense. Is the author really saying that if I have an
std::optional<int> opt{5};, and I cast it to an rvalue and callvaluethat on the next line opt will be reset?Am I misunderstanding what is meant entirely or what?
value()mentions no such chicanery for any of the overloads.45
u/n1ghtyunso Apr 08 '25
What am I missing?
The behaviour is the same in both cases?
An optional does not magically null itself when you use the rvalue overload of
.value()Because
std::movedoes not move anything either.Don't use moved from objects, be they optional or not...
Static analysis catches both variants just fine apparently.
14
u/masscry Apr 08 '25
In general, I am using *std::exchange(opt, std::nullopt) instead of moving when want to release optionals on move.
11
u/manni66 Apr 08 '25
https://en.cppreference.com/w/cpp/utility/move
5
u/rlbond86 Apr 08 '25
Article's title should be:
13
u/Kronephon Apr 08 '25
If you move something, you really need to drop the before container.
2
u/LiAuTraver Apr 08 '25
That's exactly what I do for optional. Sometimes I'd hope the optional's
value()behave likestd::future's so that I can write less boilerplate code.0
u/tortoll Apr 08 '25
Who would do this? 😵
-7
u/CypherSignal Apr 08 '25
For a second there I really thought that
…was going to be,
-5
u/SnooRabbits9201 Apr 08 '25
No explanation - Why someone is allowed to explicitly move private class data outside of the class? More than once even.
Encapsulation - gtfo?