C++ 标准的第 9.3.2.1 节规定:
在非静态 (9.3) 成员函数的主体中,关键字 this 是一个纯右值表达式,其值是调用该函数的对象的地址。类 X 的成员函数中 this 的类型是 X*。如果成员函数声明为 const,则 this 的类型为 const X*,如果成员函数声明为 volatile,则 this 的类型为 volatile X*,如果成员函数声明为 const volatile,则 this 的类型为 const挥发性 X*。
那么如果this
是纯右值,它的值类别是*this
什么?以下建议即使对象是右值,*this
也始终是左值。它是否正确?如果可能,请参考标准。
struct F;
struct test
{
void operator()(F &&) { std::cout << "rvalue operator()" << std::endl; }
void operator()(F const &&) { std::cout << "const rvalue operator()" << std::endl; }
void operator()(F &) { std::cout << "lvalue operator()" << std::endl; }
void operator()(F const &) { std::cout << "const lvalue operator()" << std::endl; }
};
struct F
{
void operator ()()
{
struct test t;
t(*this);
}
};
int main()
{
struct F f;
f();
std::move(f)();
}
输出:
lvalue operator()
lvalue operator()