ELI5 函数名称后面的"&&"关键字是什么意思

ELI5 What is the meaning '&&' keyword after a function name

本文关键字:关键字 是什么 意思 函数 ELI5      更新时间:2023-10-16

我遇到了这个代码,我不知道这是什么,有人可以向我解释一下吗?

template<class T> base{
protected:
T data;
public:
...
T&& unwrap() && { return std::move(data); }
operator T&&() && { return std::move(data); }
}

我知道operator T&&()是一个演员,但我无法弄清楚粗体&&in 的含义是什么:

运算符 T&&((和&或T&& unwrap(( &&

成员函数上的&&&限定符如下所示:

  • &限定函数将在对象的左值实例上调用
  • &&限定函数将在对象的右值实例上调用

例:

#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 Examplen"; }
// Rvalue ref qualifier
void getWhatever() && { std::cout << "This is called on rvalue instances of Examplen"; }
};
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;
}

其输出为:

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

由于在第一个函数调用中,我们在Example的左值实例上调用它,但在第二次调用中,我们将其设置为临时函数,我们调用函数,调用右值限定函数。