-
For every
a
andb
which are non-const pointers of the same type, you can doa = b;
, right? -
Inside non-const member functions the
this
keyword exists, which is a non-const pointer. So logicaly ifb
is same type asthis
you can also dothis = b;
right?
Wrong.
You cannot do this = b;
, because this
uses pointer syntax but logically this
is a reference!
But why on earth is this
syntactically a pointer but logically reference?
Can this weird behavior be corrected in the next C++ standard, by introducing a new keyword, for example me
which will be a reference not only logically but also syntactically?
(See also my attempt to solve this here: "Is it a good idea to "#define me (*this)"?")
Best Answer
this
is (likenullptr
) a constant pointer; the pointed data isconst
if and only ifthis
appears in the body of aconst
member function.You cannot change a constant pointer, like you cannot change a constant literal like
23
.So assignment to
this
likeis prohibited for the same reasons assignment to
nullptr
is forbidden: