Is the "this" pointer just a compile time thing?

Yastanub picture Yastanub · Nov 12, 2018 · Viewed 7.7k times · Source

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.

Answer

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.