GCC emits extra code for boost :: shared_ptr dereferencing

I have the following code:

#include <boost/shared_ptr.hpp> struct Foo { int a; }; static int A; void func_shared(const boost::shared_ptr<Foo> &foo) { A = foo->a; } void func_raw(Foo * const foo) { A = foo->a; } 

I thought that the compiler would create identical code, but an additional, seemingly redundant instruction is issued for the shared_ptr version.

 Disassembly of section .text: 00000000 <func_raw(Foo*)>: 0: 55 push ebp 1: 89 e5 mov ebp,esp 3: 8b 45 08 mov eax,DWORD PTR [ebp+8] 6: 5d pop ebp 7: 8b 00 mov eax,DWORD PTR [eax] 9: a3 00 00 00 00 mov ds:0x0,eax e: c3 ret f: 90 nop 00000010 <func_shared(boost::shared_ptr<Foo> const&)>: 10: 55 push ebp 11: 89 e5 mov ebp,esp 13: 8b 45 08 mov eax,DWORD PTR [ebp+8] 16: 5d pop ebp 17: 8b 00 mov eax,DWORD PTR [eax] 19: 8b 00 mov eax,DWORD PTR [eax] 1b: a3 00 00 00 00 mov ds:0x0,eax 20: c3 ret 

I'm just wondering if this is necessary, or is it just a lack of an optimizer?

Compilation with g++ 4.1.2 , -O3 -NDEBUG .

+4
source share
1 answer

This is not a redundant instruction.

The corresponding section of the first code fragment is equivalent: * P

While in the second it is equivalent: ** p

Due to the internal functions of shared_ptr, there is a second level of indirection. This is not something the optimizer can “fix”.

In any case, the difference is negligible.

EDIT:

Oops! My apologies, I am not reading your code correctly.

You pass shared_ptr BY REFERENCE to your code. This will pass it a "pointer" at the ASM level.

So, you pass a pointer to shared_ptr, and shared_ptr contains a pointer to your object.

Therefore, two levels of indirection.

Sorry for the confusion. :)

+7
source

Source: https://habr.com/ru/post/1304717/


All Articles