Reputation: 39089
In The this
pointer [class.this], the C++ standard states:
The type of
this
in a member function of a classX
isX*
.
i.e. this
is not 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!
Upvotes: 25
Views: 672
Reputation: 39089
Because in the same paragraph, it is also mentioned that this
is a prvalue
("pure 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
. 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]). And like e.g. literal true
has type bool
and not bool const
, this
is of type X*
and not X*const
.
Upvotes: 45