-
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)”?“)
3
this
is (like nullptr
) a constant pointer; the pointed data is const
if and only if this
appears in the body of a const
member function.
You cannot change a constant pointer, like you cannot change a constant literal like 23
.
So assignment to this
like
this = p; // WRONG
is prohibited for the same reasons assignment to nullptr
is forbidden:
nullptr = 0; // wrong
2
this
is NOT poorly designed. You almost never have local variables with the same names as class member names. While this construction does occur in constructors for POD or nearly POD objects, the language has a better way of dealing with this. Behold:
#include <stdio.h>
class A {
public:
A(int m1, int m2) : m1(m1), m2(m2) {}
int m1;
int m2;
};
int main()
{
A a(1, 2);
printf("%d, %dn", a.m1, a.m2);
}
I’m sure we can agree this demonstration is full of horrors, but the point is obvious. The constructor has local variables with the same name as members and initializes the members with the same names as local variables. You can run this program and get the output “1, 2”.
Also, in C++ we expect that we may declare functions having good parameter names (for hinting) and bad names for the actual implementation. This can even be done for inline functions if we bother to declare them separately rather than bodily in the class definition.
For all of these reasons, a member function rarely needs to access its class explicitly but only its pointer, thus the this
keyword is a pointer.
Historical artifact: this
was once not const
and could be assigned to. This was a bad idea.
One can make an argument that this
is a bit clumsy.
Having a self
-reference instead would probably feel a bit more natural nowadays:
Its type could then carry slightly more information in it than the type of this
can, namely:
- Whether the member-function was guaranteed called on an rvalue-reference, and
- that it actually always refers to an object.
Still, when C++ finally got references (invented for operator-overloading, I think), the decision on this
was already ancient history. And backwards-compatibility is no laughing matter.