Daniel D.
Daniel D.

Reputation: 198

C++ acess object via pointer instead of direct access

In some code i have seen the following: (&object)->something.

  1. Is there any advantage to object.something ?
  2. Does the compiler somehow optimize such code, or is it faster in any way?

Upvotes: 0

Views: 60

Answers (1)

hauron
hauron

Reputation: 4668

If operator& is not overloaded it's essentially the same https://godbolt.org/g/iPTjRY:

auto v_1 = f_1.get(); 
auto v_2 = (&f_1)->get();

resolved to pretty much the same:

lea rax, [rbp-12]               ; load object address
mov rdi, rax                    ; move object address into rdi, not sure why not just: 'lea rdi, [rbp-12]'
call Foo::get() const           ; invoke the subroutine
mov DWORD PTR [rbp-4], eax      ; save the result at [rbp-4]

(already with no optimizations they are the same; with optmizations turned on... the entire calls get discarded, so that's left for the curious reader)

Upvotes: 4

Related Questions