Search code examples
c++c++11constants

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


Solution

  • const& means that this overload will be used only for const, non-const and lvalue objects, such as:

    const A a = A();
    *a;
    

    & means that this overload will be used only for non-const objects:

    A a;
    *a;
    

    && means that this overload will be used only for rvalue objects:

    *A();
    

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