Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const& , & and && specifiers for member functions in C++

Recently I was reading through the API of boost::optional and came across the lines:

T const& operator *() const& ; T&       operator *() & ; T&&      operator *() && ; 

I also wrote my own program that defines member functions as const&, & and && (Note that I am not speaking about the return type, but the specifiers just before the semi-colons) and they seems to work fine.

I know what it means to declare a member function const, but can anyone explain what it means to declare it const&, & and &&.

like image 945
john_zac Avatar asked Jan 21 '15 12:01

john_zac


2 Answers

const& means, that this overload will be used only for const, non-const and lvalue object.

const A a = A(); *a; 

& means, that this overload will be used only for non-const object.

A a; *a; 

&& means, that this overload will be used only for rvalue object.

*A(); 

for more information about this feature of C++11 standard you can read this post What is "rvalue reference for *this"?

like image 122
ForEveR Avatar answered Sep 24 '22 17:09

ForEveR


It is member function ref-qualifiers, it is one of the features added in C++11. It is possible to overload non-static member functions based on whether the implicit this object parameter is an lvalue or an rvalue by specifying a function ref-qualifier (some details).

To specify a ref-qualifier for a non-static member function, you can either qualify the function with & or &&.

#include <iostream> struct myStruct {     void func() & { std::cout << "lvalue\n"; }     void func() &&{ std::cout << "rvalue\n"; } };  int main(){     myStruct s;     s.func();            // prints "lvalue"     std::move(s).func(); // prints "rvalue"     myStruct().func();   // prints "rvalue" } 
like image 22
Alper Avatar answered Sep 24 '22 17:09

Alper