繁体   English   中英

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

[英]If `this` is not const, why can't I modify it?

this指针 [class.this]中,C ++标准规定:

的类型的this类中的成员函数XX*

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标准中提到的示例是调用不返回引用的函数或者像1true3.5f这样的文字的3.5f this -pointer不是一个变量,它更像是一个文字扩展到调用该函数的对象地址 ([class.this])。 并且例如文字true具有类型bool不是 bool constthis是类型X*不是 X*const

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM