在 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
,但它确实是!
答案 0 :(得分:45)
因为在同一段中,还提到this
是prvalue
(“纯右值”)。
纯rvalue标准中提到的示例是调用不返回引用的函数或1
,true
或3.5f
等文字的结果。 this
- 指针不是变量,它更像是一个文字,它扩展为函数被称为([class.this])的对象的地址。和例如文字true
的类型为bool
,而不是 bool const
,this
的类型为X*
而不是 X*const
。