Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trailing const& or && on function declaration [duplicate]

Tags:

c++

c++11

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&?

like image 897
Yuushi Avatar asked Sep 05 '13 04:09

Yuushi


People also ask

What is the purpose of the trailing const?

The trailing const on inspect() member function means that the abstract (client-visible) state of the object isn't going to change.

What does a const method mean?

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.

What does const at the end of a function mean?

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.

What does adding const after a function mean C++?

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.


1 Answers

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.

like image 200
aaronman Avatar answered Oct 22 '22 01:10

aaronman