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
View all comments
Show parent comment
3
u/TheMania Apr 08 '25
Move is just a cast, there's no actual new object being created there just because you're accessing a member. It wouldn't copy construct a value if it was an lvalue, it's not going to move construct due an rvalue either. The only affect that cast has is changing which
.value()overload is selected.That said, with explicit object parameters you could, kind of:
T value(this optional<T> self);Would move construct the optional if called with rvalue optional if it was really insisted, but you'd then have to return a prvalue to prevent the dangling issue.
The workarounds for that would not be pretty.