ref-qualifier
ref-qualifier
https://en.cppreference.com/w/cpp/language/member_functions
Member functions with ref-qualifier
An implicit object member function can be declared with no ref-qualifier, with an lvalue ref-qualifier (the token & after the parameter list) or the rvalue ref-qualifier (the token && after the parameter list). During overload resolution, an implicit object member function with a cv-qualifier sequence of class X is treated as follows:
- no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument
- lvalue ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X
- rvalue ref-qualifier: the implicit object parameter has type rvalue reference to cv-qualified X
example 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#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"
}
从示例中可以看出,成员函数用右值限定符修饰后只能通过右值对象调用,而左值限定符修饰的成员函数则可以通过左值对象和右值对象调用。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!