成员函数上的常量引用限定符 [英] Const reference qualifier on a member function
问题描述
我在那里的答案中看到了:通过右值引用返回是否更有效?
I have seen in an anwser there: Is returning by rvalue reference more efficient?
成员函数定义:
Beta_ab const& getAB() const& { return ab; }
我熟悉成员函数上的 cv-qualifier ( const
),但不熟悉 const&
.
I am familiar with the cv-qualifier (const
) on member functions, but not const&
.
最后一个 const&
是什么意思?
推荐答案
&
是 ref-qualifier .引用限定符是C ++ 11中的新增功能,尚不受所有编译器支持,因此您目前并不经常看到它们.它指定只能在左值(而不是右值)上调用此函数:
The &
is a ref-qualifier. Ref-qualifiers are new in C++11 and not yet supported in all compilers, so you don't see them that often currently. It specifies that this function can only be called on lvalues (and not on rvalues):
#include <iostream>
class kitten
{
private:
int mood = 0;
public:
void pet() &
{
mood += 1;
}
};
int main()
{
kitten cat{};
cat.pet(); // ok
kitten{}.pet(); // not ok: cannot pet a temporary kitten
}
结合cv限定符 const
,这意味着您只能在左值上调用此成员函数,而这些值可能是const.
Combined with the cv-qualifier const
, it means that you can only call this member function on lvalues, and those may be const.
这篇关于成员函数上的常量引用限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!