在C++标准中,关于The this
pointer [class.this]的规定如下:
在类
X
的成员函数中,this
的类型为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
不是一个变量,因此我们不能声明它是常量还是非常量。 - fatihk