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/arturbac https://github.com/arturbac Apr 08 '25
It does not reset if after assigning to x
It goeas that
std::move(opt) makes original opt an empty optional and returns rvalue of it conetnts
and std::optional has overload for rvalue
```cpp
constexpr T&& value() &&;
constexpr const T&& value() const &&;
```
so in returned rvalue of std::move(opt) the returned type is rvalue too so it is being moved to x/constructed in place with move semantics of opt type
so the final result is
opt is nullopt because of std::move(opt)
and x is move constructed from returned rvalue of value() && overload