Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

In The this pointer [class.this], the C++ standard states:

The type of this in a member function of a class X is X*.

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!

like image 200
Sebastian Mach Avatar asked Jun 17 '13 12:06

Sebastian Mach


People also ask

Can you modify a const object?

The property of a const object can be change but it cannot be change to reference to the new object.

Can you modify const reference?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

Can you modify const in C?

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.

Can you redefine const?

The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned.


1 Answers

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.

like image 141
Sebastian Mach Avatar answered Oct 02 '22 23:10

Sebastian Mach