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限定符,则始终可以调用该函数,而不管通过其调用表达式的值类别是什么:
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/64180852/

相关文章:

c++ - 无法使用Nuget安装软件包

c++ - 多线程妄想症

c++ - 三元运算符和增量运算符

c++ - u'\U0001ABCD' 是否具有实现定义的值或格式错误?

c++ - 我可以用静态的、constexpr、类内初始化的数据成员做什么?

c++ - 使用 C++11 占位符作为 lambdas?

c++ - 如果给定的模板参数提供类型定义,则使用 sfinae 启用构造函数

c++ - 使用 linux 自动工具

c++ - C++中的数组分配在具有不同长度的堆栈上

c++ - 如何在类上下文中使用 std::mutex