gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:25 25 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/39779442/

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