[英]If `this` is not const, why can't I modify it?
In The this
pointer [class.this], the C++ standard states: 在this
指针 [class.this]中,C ++标准规定:
The type of
this
in a member function of a classX
isX*
. 的类型的this
类中的成员函数X
是X*
。
ie this
is not const
. 即this
不是const
。 But why is it then that 但那为什么呢
struct M {
M() { this = new M; }
};
gives 给
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)
In other words, this
is not const
, but it really is! 换句话说, this
不是const
,但它确实是!
Because in the same paragraph, it is also mentioned that this
is a prvalue
("pure rvalue"). 因为在同一段中,还提到this
是一个prvalue
(“纯rvalue”)。
Examples mentioned in the standard for pure rvalue are the result of calling a function which does not return a reference, or literals like 1
, true
or 3.5f
. 纯rvalue标准中提到的示例是调用不返回引用的函数或者像1
, true
或3.5f
这样的文字的3.5f
。 The this
-pointer is not a variable, it's more like a literal that expands to the address of the object for which the function is called ([class.this]). this
-pointer不是一个变量,它更像是一个文字扩展到调用该函数的对象的地址 ([class.this])。 And like eg literal true
has type bool
and not bool const
, this
is of type X*
and not X*const
. 并且例如文字true
具有类型bool
而不是 bool const
, this
是类型X*
而不是 X*const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.