[英]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.