Why does moving std::optional not reset state

  • A+
Category:Languages

I was rather surprised to learn that the move constructor (and assignment for that matter) of std::optional does not reset the optional moved from, as can be seen in [19.6.3.1/7] which states "bool(rhs) is unchanged."

This can also be seen by the following code:

#include <ios> #include <iostream> #include <optional> #include <utility>  int main() {   std::optional<int> foo{ 0 };   std::optional<int> bar{ std::move(foo) };    std::cout << std::boolalpha             << foo.has_value() << '/n'  // true             << bar.has_value() << '/n'; // true } 

This seems to contradict other instances of moving in the standard library such as with std::vector where the container moved from is usually reset in some way (in vector's case it is guaranteed to be empty afterwards) to "invalidate" it even if the objects contained within it themselves have been moved from already. Is there any reason for this or potential use case this decision is supposed to support such as perhaps trying to mimic the behavior of a non-optional version of the same type?

 


Unless otherwise specified, a moved-from object of class type is left in a valid but unspecified state. Not necessarily a "reset state", and definitely not "invalidated".

For primitive types , moving is the same as copying, i.e. the source is unchanged.

The defaulted move-constructor for a class type with primitive members will move each member, i.e. leave the primitive members unchanged; a user-defined move constructor might or might not "reset" them.

A moved-from vector may or may not still have elements in it. We would expect it not to, since that's efficient, but it cannot be relied on.

A moved-from std::string may still have elements in it, because of Small String Optimization.


move on std::optional is actually specified by the standard (C++17 [optional.ctor]/7). It is defined as doing move on the contained type, if present. It does not turn a valued optional into a valueless optional.

So it is actually expected that your code outputs true true, and the actual contained value in foo should stay the same too.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: