[Solved] performance of member variable access with ‘this->’


Accessing a member inside a non-static member function with and without this-> results in the same machine code. The latter is syntactic sugar for the former. The code

class A {
public:
    int a;
    A() {
        a = 1;
    }
};

class B {
public:
    int b;
    B() {
        this->b = 1;
    }
};

int main() {
    A a;
    B b;
    return 0;
}

is translated without optimization to

main:                                   # @main
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     dword ptr [rbp - 4], 0
        lea     rdi, [rbp - 8]
        call    A::A() [base object constructor]
        lea     rdi, [rbp - 16]
        call    B::B() [base object constructor]
        xor     eax, eax
        add     rsp, 16
        pop     rbp
        ret
A::A() [base object constructor]:                              # @A::A() [base object constructor]
        push    rbp
        mov     rbp, rsp
        mov     qword ptr [rbp - 8], rdi
        mov     rax, qword ptr [rbp - 8]
        mov     dword ptr [rax], 1
        pop     rbp
        ret
B::B() [base object constructor]:                              # @B::B() [base object constructor]
        push    rbp
        mov     rbp, rsp
        mov     qword ptr [rbp - 8], rdi
        mov     rax, qword ptr [rbp - 8]
        mov     dword ptr [rax], 1
        pop     rbp
        ret

Dereferencing a pointer does not copy the object but yields a reference to the object. Otherwise code like

int a(0);
int pa = &a;
*pa = 12;
std::cout << a << '\n'; // prints 12

would not work as expected. Also this access is by reference:

class A {
public:
    int a(0);
    int b(0);
    int c(0);
    A() {
        a = 1;
        this->b = 2;
        (*this).c = 3;
        std::cout << a << " " << b << " " << c << '\n'; // prints 1 2 3
    }
};

If it was a copy you could not set the value of the member variables. Every time you can change the value of the origin, it is a reference and not a copy.

solved performance of member variable access with ‘this->’