These are the signatures, according to Cppreference:
constexpr T& value() &;
constexpr const T& value() const &;
constexpr T&& value() &&;
constexpr const T&& value() const &&;
What's the point of using &/const&
and &&/const&&
?
Especially, I don't understand the point of having a const&&
overload. const
objects shouldn't be moved, so why would we have this?
It's all about being in a generic template context. The standard library here needs to support all the possible scenarios (you an imagine and the ones you can't imagine) because I assure you some C++ project somewhere does use it.
So if you have a user defined type
X
as follows:where
foo
is optimized for const temporary (foo (4)
) vs const non-temporary (foo (2)
) the standard library needs to support that withstd::optional
.If
std::optinal
would be missing theconstexpr const T&& value() const &&;
when the user has astd::optional<X> const &&
(it can be in a generic template context) and tries to callfoo
on it thefoo (2)
would be called instead offoo (4)
.What I mean by calling
foo
here:There is a worst scenario. Imagine a user type type
Y
like so:In this case trying to access
foo
on a const temporary would result in a compiler error instead of calling the expectedfoo 4
overload.