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

时间:2013-06-17 12:04:56

标签: c++ this-pointer

this指针 [class.this]中,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,但它确实是!

1 个答案:

答案 0 :(得分:45)

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

纯rvalue标准中提到的示例是调用不返回引用的函数或1true3.5f等文字的结果。 this - 指针不是变量,它更像是一个文字,它扩展为函数被称为([class.this])的对象的地址。和例如文字true的类型为bool,而不是 bool constthis的类型为X*不是 X*const