Ref-qualified member functions serve the purpose of allowing a member function to be called on an rvalue reference. This enables the function to modify the object it is called on, even if the object itself is an rvalue. By using the ref-qualifier syntax, the function can be overloaded to have different behavior depending on whether it is called on an lvalue or an rvalue. This provides flexibility and efficiency in handling object references, enhancing the overall functionality and performance of the code.

32
1个回答

57

请看下面的内容:

在重载决议时,对于类X的非静态cv限定成员函数,如果它没有ref-qualifiers或者有左值引用限定符,那么它被视为一个接受隐式参数类型为cv限定的X的左值引用的函数。否则(如果它具有右值引用限定符),它被视为一个接受隐式参数类型为cv限定的X的右值引用的函数。

示例

#include <iostream>
struct S {
    void f() & { std::cout << "lvalue\n"; }
    void f() &&{ std::cout << "rvalue\n"; }
};
 
int main(){
    S s;
    s.f();            // prints "lvalue"
    std::move(s).f(); // prints "rvalue"
    S().f();          // prints "rvalue"
}

因此,在重载决议期间,如果调用程序对象是 lvalue,则编译器会查找带有 & 限定符的函数,如果调用程序对象是 rvalue,则编译器会查找带有 && 限定符的函数。


27
如果所有冷漠的标准用明确简洁的例子来增强,这个世界将变得更美好! - sunny moon
1
@Nick,是的。 - user4290866
@sunnymoon,你能否用简单的话解释一下这个引语? - John
@John 基本上,您可以根据该类的实例将其重载为类或结构成员函数 - lvalue(定位器值,考虑“命名”,“长期存在”或“位于堆栈或堆中的某个命名内存区域”)或rvalue(即非定位器值,考虑“匿名”,“临时”或“位于临时内存区域,可能是处理器寄存器”)。这就是为什么lvalue Sf()打印“lvalue”,而rvalue Sf()打印“rvalue”的原因。Ref-qualifiers 是在 void f() 之后的 &(lvalue)和 &&(rvalue)。 - sunny moon
所选的 ref-qualified 成员基于函数中的 'this' 是左值还是右值。使用技术术语“调用对象”意味着“this”。 - rm1948
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接