c++ - 成员函数声明的参数列表后的单个&符号是什么意思?

标签 c++ c++11

来自答案here .

class wrap {
public:
   operator obj() const & { ... }   //Copy from me.
   operator obj() && { ... }  //Move from me.
private:
   obj data_;
};

我知道 && 表示当对象是右值引用时将调用该成员。但是单个&符号是什么意思?它与没有符号有何不同?

最佳答案

这意味着当对象是左值引用时将调用该成员。

[C++11: 9.3.1/5]: A non-static member function may be declared with a ref-qualifier (8.3.5); see 13.3.1.

[C++11: 13.3.1/4]: For non-static member functions, the type of the implicit object parameter is

  • “lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier
  • “rvalue reference to cv X” for functions declared with the && ref-qualifier

where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. [..]

(and some more rules that I can't find)

如果没有ref-qualifier,函数总是可以被调用,不管你调用它的表达式的值类别是什么:

struct foo
{
    void bar() {}
    void bar1() & {}
    void bar2() && {}
};

int main()
{
    foo().bar();  // (always fine)
    foo().bar1(); // doesn't compile because bar1() requires an lvalue
    foo().bar2();
    
    foo f;
    f.bar();      // (always fine)
    f.bar1();
    f.bar2();     // doesn't compile because bar2() requires an rvalue
}

Live demo (感谢 Praetorian)

关于c++ - 成员函数声明的参数列表后的单个&符号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39779442/

相关文章:

c++ - 为什么我将垃圾值作为输出?

c++ - 从 Glib 移植到 Qt

c++ - 如何在 constexpr 函数内部的字符串文字上静态断言条件?

C++11 自动创建整数到枚举值映射

c++ - Qt 虚拟键盘和 QInputContextFactory

c++ - Portaudio 无法识别所有音频设备

c++ - std::function 和错误:没有匹配的函数来调用

c++ - 将 vector 指针 move 到 C++ 中的 vector 派生类?

c++ - 如何检测整个周期的C++随机引擎已经被消耗

C++:从另一个 vector 指向对象的指针 vector