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

C++C++11Constants

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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 https://stackoverflow.com/questions/8610571/what-is-rvalue-reference-for-this

Solution 2 - C++

It is a 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"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjohn_zacView Question on Stackoverflow
Solution 1 - C++ForEveRView Answer on Stackoverflow
Solution 2 - C++AlperView Answer on Stackoverflow