Is the "this" pointer just a compile time thing?
I asked myself whether the this
pointer could be overused since I usually use it every single time I refer to a member variable or function. I wondered if it could have performance impact since there must be a pointer which needs to be dereferenced every time. So I wrote some test code
struct A {
int x;
A(int X) {
x = X; /* And a second time with this->x = X; */
}
};
int main() {
A a(8);
return 0;
}
and surprisingly even with -O0
they output the exact same assembler code.
Also if I use a member function and call it in another member function it shows the same behavior. So is the this
pointer just a compile time thing and not an actual pointer? Or are there cases where this
is actually translated and dereferenced? I use GCC 4.4.3 btw.
So is the this pointer just a compile time thing and not an actual pointer?
It very much is a run time thing. It refers to the object on which the member function is invoked, naturally that object can exist at run time.
What is a compile time thing is how name lookup works. When a compiler encounters x = X
it must figure out what is this x
that is being assigned. So it looks it up, and finds the member variable. Since this->x
and x
refer to the same thing, naturally you get the same assembly output.
It is an actual pointer, as the standard specifies it (§12.2.2.1):
In the body of a non-static (12.2.1) member function, the keyword
this
is a prvalue expression whose value is the address of the object for which the function is called. The type ofthis
in a member function of a classX
isX*
.
this
is actually implicit every time you reference a non-static member variable or member function within a class own code. It is also needed (either when implicit or explicit) because the compiler needs to tie back the function or the variable to an actual object at runtime.
Using it explicitly is rarely useful, unless you need, for example, to disambiguate between a parameter and a member variable within a member function. Otherwise, without it the compiler will shadow the member variable with the parameter (See it live on Coliru).