gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:57:26 27 4
gpt4 key购买 nike

来自答案 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/21861148/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com