Ref-qualified成员函数的目的是什么? [英] What is the purpose of Ref-qualified member functions ?
问题描述
在阅读 http://en.cppreference.com/w/cpp/language/ member_functions ,我遇到了一些事情,我以前没有见过: lvalue / rvalue Ref-qualified member functions
。他们的目的是什么?
While reading http://en.cppreference.com/w/cpp/language/member_functions, I came across something, I haven't seen before: lvalue/rvalue Ref-qualified member functions
. What would be their purpose ?
推荐答案
请在下面阅读:
在重载解析期间,类X的非静态cv限定成员函数被视为一个函数,如果没有参照限定符,则采用类型为lvalue的隐式参数引用cv限定的X;如果它有lvalue ref-qualifier。否则(如果它有rvalue ref-qualifier),它被视为一个函数,它采用类型为rvalue的隐式参数引用cv限定的X.
During overload resolution, non-static cv-qualified member function of class X is treated as a function that takes an implicit parameter of type lvalue reference to cv-qualified X if it has no ref-qualifiers or if it has the lvalue ref-qualifier. Otherwise (if it has rvalue ref-qualifier), it is treated as a function taking an implicit parameter of type rvalue reference to cv-qualified X.
示例
Example
#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"
}
因此在重载解析过程中,编译器会查找函数& -qualified如果调用对象是 lvalue
或对于函数& -qualified如果调用对象是右值
。
So during overload resolution the compiler looks for the function &-qualified if the caller object is an lvalue
or for the function &&-qualified if the caller object is an rvalue
.
这篇关于Ref-qualified成员函数的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!