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
Xas follows:where
foois optimized for const temporary (foo (4)) vs const non-temporary (foo (2)) the standard library needs to support that withstd::optional.If
std::optinalwould 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 callfooon it thefoo (2)would be called instead offoo (4).What I mean by calling
foohere:There is a worst scenario. Imagine a user type type
Ylike so:In this case trying to access
fooon a const temporary would result in a compiler error instead of calling the expectedfoo 4overload.