Comment

Comment by UkrainianJew

That's because you are explicitly telling the compiler to create a copy of your shared pointer, that involves incrementing/decrementing the counter:

  static int add_numbers(std::shared_ptr<Data> p) {
      return p->a + p->b;
  }
Try this:

  static int add_numbers(const std::shared_ptr<Data> &p) {
      return p->a + p->b;
  }
You'll get 4 instructions (don't forget to put __attribute__((noinline)) on add_numbers()):

  add_numbers(std::shared_ptr<Data>&):
          mov     rdx, QWORD PTR [rdi]
          mov     eax, DWORD PTR [rdx+4]
          add     eax, DWORD PTR [rdx]
          ret
The only difference is that Rust physically placed the structure in 2 registers (hence just 1 instruction), while C++ physically placed it into memory (hence the need to 2 extra instructions fetching the values).

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton