std::optional::value()
has the following two overloads
constexpr T& value() &;
constexpr const T & value() const &;
constexpr T&& value() &&;
constexpr const T&& value() const &&;
What is the point of returning a const rvalue reference?
The only reason I can think of is to enable the compiler to help catch undefined behavior in (really really weird) cases like the following
auto r = std::cref(const_cast<const std::optional<int>&&>(
std::optional<int>{}).value());
Where if the std::optional::value()
had returned a const T&
then the above code would compile and would lead to undefined behavior when the r
reference_wrapper
was used later.
Is there any other corner case in mind with the above returning a const T&&
?