I was looking at the API for std::optional<T>
on cppreference. I was curious how value_or
would work. Looking there, it seems there are two overloads:
template< class U >
constexpr T value_or( U&& value ) const&;
template< class U >
T value_or( U&& value ) &&;
What are the const&
and &&
trailing the function declaration? What is the difference between declaring a function as const
and declaring it as const&
?
The trailing const on inspect() member function means that the abstract (client-visible) state of the object isn't going to change.
The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const : const foobar fb; fb.
Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class.
An ampresand after the function means that this
must be an lvalue, conversely the double ampersand means it must be an rval, the const just says that it's a nonmodifiable lval or rval
So a function qualified with &
only works on a modifiable lval and if qualified with &&
only works on an rval. I guess a const &&
really makes no sense since a const &
can bind to a temporary so the const qualifier only does anything for the lval.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With