简体   繁体   中英

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

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

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

ie 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!

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 eg literal true has type bool and not bool const , this is of type X* and not X*const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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