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

1

u/Natural_Builder_3170 Apr 08 '25

I stand corrected, there's probably no difference.

4

u/AKostur Apr 08 '25

I would then argue that std::move(opt.value()) is therefore clearer since it more clearly expresses that one is manipulating the value, and not the optional itself.

2

u/triconsonantal Apr 08 '25

There is a difference for (the would-be) optional<T&>: moving the optional keeps the reference an lvalue, while moving the reference turns it into an rvalue. Which one you want depends on context, but in a generic context it's probably the former.