我什么时候应该使用 const 呢?
When should I use const& to this?
我找到了这样的代码:
class foo{
int a;
public:
foo(int v) : a{v} {}
bool operator==(const foo& rhs) const&{
return (rhs.a == a);
}
};
它编译并运行。
我想知道在运算符==中引用 (&) 有什么好处(或坏处)。
为T.C。已经在评论中指出,这个原因不是 "to accept only lvalues"。 const
引用可以很好地绑定到右值。
原因是只有在所有重载都指定一个值类别时,函数才能在隐式对象参数的值类别上重载。也就是说,当您添加仅匹配右值的 &&
重载时,它将不会编译,除非您将 &
添加到现有重载。
在 13.1 中,规则的措辞如下:
Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same
template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.
并举个例子
class Y
{
void h() &;
void h() const &; // OK
void h() &&; // OK, all declarations have a ref-qualifier
void i() &;
void i() const; // ill-formed, prior declaration of i
// has a ref-qualifier
};
我找到了这样的代码:
class foo{
int a;
public:
foo(int v) : a{v} {}
bool operator==(const foo& rhs) const&{
return (rhs.a == a);
}
};
它编译并运行。
我想知道在运算符==中引用 (&) 有什么好处(或坏处)。
为T.C。已经在评论中指出,这个原因不是 "to accept only lvalues"。 const
引用可以很好地绑定到右值。
原因是只有在所有重载都指定一个值类别时,函数才能在隐式对象参数的值类别上重载。也就是说,当您添加仅匹配右值的 &&
重载时,它将不会编译,除非您将 &
添加到现有重载。
在 13.1 中,规则的措辞如下:
Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.
并举个例子
class Y { void h() &; void h() const &; // OK void h() &&; // OK, all declarations have a ref-qualifier void i() &; void i() const; // ill-formed, prior declaration of i // has a ref-qualifier };