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!
The property of a const object can be change but it cannot be change to reference to the new object.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.
The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With