-2

I met this code and i dont know what is this, can someone explain to me?

template<class T> base{

protected:

T data;

public:

...

T&& unwrap() && { return std::move(data); }

operator T&&() && { return std::move(data); }

}

I know operator T&&() is a cast operator but i cant figure out what is the meaning of the bold && in:

operator T&&() && or T&& unwrap() &&

Justin
  • 149
  • 1
  • 11
  • 5
    Those are [*ref-qualified* function specifiers](http://en.cppreference.com/w/cpp/language/member_functions#const-.2C_volatile-.2C_and_ref-qualified_member_functions). – Some programmer dude Jun 13 '18 at 10:40
  • There is a nice example in the (currently accepted) answer to [SO: What is “rvalue reference for *this”?](https://stackoverflow.com/a/8610728/7478597) which appears a bit more practical to me like the one on cppreference... – Scheff's Cat Jun 13 '18 at 11:31
  • 1
    OT: ELI5 ... Explain like I'm 5. IMHO, 5 is too young to learn C++... – Scheff's Cat Jun 13 '18 at 11:34

1 Answers1

0

The && and & qualifiers on a member function like that indicates the following:

  • The & qualified function will be called on lvalue instances of the object
  • The && qualified function will be called on rvalue instances of the object

Example:

#include <iostream>

class Example
{
private:
    int whatever = 0;

public:
    Example() = default;

    // Lvalue ref qualifier
    void getWhatever() & { std::cout << "This is called on lvalue instances of Example\n"; }

    // Rvalue ref qualifier
    void getWhatever() && { std::cout << "This is called on rvalue instances of Example\n"; }
};

int main()
{
    // Create example
    Example a;

    // Calls the lvalue version of the function since it's called on an lvalue
    a.getWhatever();

    // Calls rvalue version by making temporary
    Example().getWhatever();

    return 0;
}

The output of this is:

This is called on lvalue instances of Example
This is called on rvalue instances of Example

Since in the first function call we are calling it on an lvalue instance of Example, but in the second call we are making it a temporary on which we call the function, invoking the rvalue qualified function.

Carl
  • 2,057
  • 1
  • 15
  • 20