如果"this"不是常量,为什么我不能修改它?

If `this` is not const, why can't I modify it?

本文关键字:不能 修改 为什么 this 常量 如果      更新时间:2023-10-16

In this指针 [class。, c++标准规定:

的成员函数中this的类型一个类 X X*

this不是const。但是为什么

struct M {
    M() { this = new M; }
};

error: invalid lvalue in assignment  <-- gcc
'=' : left operand must be l-value   <-- VC++
'=' : left operand must be l-value   <-- clang++
'=' : left operand must be l-value   <-- ICC
(source: some online compiler frontends)

换句话说,this不是const,但它确实是!

因为在同一段中,还提到thisprvalue("纯右值")。

纯右值标准中提到的例子是调用不返回引用的函数的结果,或者像1true3.5f这样的字面量。this -指针不是一个变量,它更像是一个展开为调用函数的对象 ([class.this])的地址的字面值。例如,文字true的类型是bool不是 bool const, this的类型是X*不是 X*const