2

I'm using godbolt.org to compare the compiled code, with -O3 as optimization flag.

I tried a few things, as currently I'm trying to optimize some code, and so I came to this:

enter image description here

So it comes out that passing unique_ptr requires more indirections than passing a raw or even wrapped pointer. Why does it happen, and how can I overcome it?

  • 2
    because it has to deal with temporaries? https://stackoverflow.com/questions/54225864/does-passing-a-unique-ptr-by-value-have-a-performance-penalty-compared-to-a-pl – Biggy Smith May 13 '22 at 16:46
  • 1
    Add a destructor to MyPtr and redo the test. I suspect this has to do with exception handling and needing to call the destructor when/if the stack unwinds. – Martin York May 13 '22 at 16:51
  • 1
    Please put the code as a text and not an image, and if possible, please change the godbolt link so to reference your specific example. Note that such case should not be a problem if the function is inlined or if the pointer is used several time. – Jérôme Richard May 13 '22 at 17:00
  • @MartinYork the `*` operator for `std::unique_ptr` is noexcept. There are no exceptions that can happen in `f2()`; only a read access violation is possible for the empty unique_ptr, but this possibility exists `int*` and `MyPtr` as well... – fabian May 13 '22 at 17:36
  • 1
    If you actually had to call the functions, `f2()` has different semantics than all the other functions. Since you're passing the `unique_ptr` by value, that means `f2` is taking ownership of the `unique_ptr`, so nominally it should release the pointer. Why that, in particular, doesn't appear in the generated code, I'm not sure. – Kyle May 13 '22 at 17:54
  • 1
    @Kyle Whether function parameters are destroyed at the end of the function or at the end of the full-expression in the caller is implementation-defined and depends on the ABI, e.g. on Windows it will be destroyed at the end of the function body, while in the Itanium ABI it will be destroyed by the caller. It you move the pointer to a local variable instead, you get destruction of the pointer at the end of the function body in all ABIs. – user17732522 May 13 '22 at 18:06
  • 1
    Don't post pictures of text. You had Godbolt open to take the screenshot, but you still just pasted a link not to your code :(. Click the "share" button along the top row to generate a short link to the actual code, and include that in your question (or preferably a full link to guard against link rot, use control-L on stack overflow so you can easily put a title on the hyperlink). Also don't post pictures of text when you could just use `code formatting` blocks for C++ and asm. – Peter Cordes May 13 '22 at 18:32

0 Answers0