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?