在该this指针 [class.this],C++标准规定:
类的
this成员函数的类型X是X*.
即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,true或3.5f.的this终场是不是一个变量,它更像一个可扩展到一个字面的量,函数被调用的对象的地址([class.this]).并且像文字true有类型bool而不是 bool const,this类型X*而不是 X*const.