如果`this`不是const,为什么我不能修改它?

Seb*_*ach 25 c++ this-pointer

this指针 [class.this],C++标准规定:

类的this成员函数的类型XX*.

this不是const.但那为什么呢

struct M {
    M() { this = new M; }
};
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*ach 45

因为在同一段中,还提到它this是一个prvalue("纯rvalue").

在纯右值的标准提到的例子是呼叫不返回一个引用,或类似的文字的功能的结果1,true3.5f.的this终场是不是一个变量,它更像一个可扩展到一个字面的量,函数被调用的对象的地址([class.this]).并且像文字true有类型bool不是 bool const,this类型X*不是 X*const.

  • @busy_wait:不.它是正式未指定的,但例如MSVC++使用`ECX`寄存器.你不能拿一个寄存器的地址. (5认同)
  • @busy_wait在C++中,值具有*类型*和**类别.*`this`的类型是`X*`,其值类别是prvalue.这是非本能的?`this`必须是一个prvalue('&this`毫无意义) - 为什么在它不可修改的情况下使它的类型为`X*const`? (3认同)
  • @Angew:人们必须补充说,有些语言中`this`(或其等价物)不可修改.例如蟒:`类X:DEF __init __(个体):自= X()S = X()'< - 这将给一个`最大recusion深度exceeded`而不是编译错误. (3认同)