[英]If `this` is not const, why can't I modify it?
在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
,但它确实是!
因为在同一段中,还提到this
是一个prvalue
(“纯rvalue”)。
纯rvalue标准中提到的示例是调用不返回引用的函数或者像1
, true
或3.5f
这样的文字的3.5f
。 this
-pointer不是一个变量,它更像是一个文字扩展到调用该函数的对象的地址 ([class.this])。 并且例如文字true
具有类型bool
而不是 bool const
, this
是类型X*
而不是 X*const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.