成员函数声明的参数列表后的单个“&”号是什么意思? [英] What does the single ampersand after the parameter list of a member function declaration mean?

查看:114
本文介绍了成员函数声明的参数列表后的单个“&”号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从答案的此处

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

我知道&&的意思当对象是右值引用时将调用该成员。但是,单个&号是什么意思?

I know the && means that the member will be invoked when the object is an rvalue reference. But what does the single ampersand mean? How is it different than without the ampersand?

推荐答案

这意味着在对象是左值引用时将调用该成员。 / p>

It means the member will be invoked when the object is an lvalue reference.


[C ++ 11:9.3.1 / 5]:非静态成员函数可能用 ref-qualifier (8.3.5)声明;参见13.3.1。

[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]:对于非静态成员函数,隐式对象参数的类型为

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


  • cv X 表示没有 ref-qualifier 或使用& ref-qualifier
  • $声明的函数b $ b
  • cv X 的右值引用,该函数使用&& ref-qualifier

  • "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

其中 X 是该函数所在的类成员,并且 cv 是成员函数声明中的 cv资格 [..]

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

(还有一些我找不到的规则)

如果没有 ref-qualifier ,则始终可以调用该函数,无论您通过其调用表达式的值类别是什么:

Without a ref-qualifier, the function can always be invoked, regardless of the value category of the expression through which you're invoking it:

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
}

这篇关于成员函数声明的参数列表后的单个“&”号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆