1

In the ARM procedure call standard for the 32-bit architecture, it is possible to return a struct with a single data member in a register, rather than on the stack.

The size of a C++ unique_ptr is only the size of a single pointer, so I would expect it to be returned in a register, too. But, at least with gcc, that's not the case.

I fail to understand what it is with unique_ptr that defeats this possible optimization? Could unique_ptr be implemented in such a way as to take advantage of the small struct optimization, or is there an insurmountable obstacle?

The most important downside of having unique_ptr returned on the stack, is that an additional register is consumed in the procedure call to hold the address of the location where to store the result. Hence I conjecture that there would be room for some optimization, at least on the ARM platform, but possibly for others, too.

sh-
  • 941
  • 6
  • 13
  • 1
    It's probably because `unique_ptr` is not trivial. It can't be copied and must be moved around and moving modifies two objects, not just one. – NathanOliver Jul 23 '23 at 13:16
  • That's the high-level view of unique_ptr. But at the machine level it is pointers. You may be right with your conjecture, but what is the actual rule in the ABI that prevents it? – sh- Jul 23 '23 at 13:39
  • 2
    Related to [why-can-a-t-be-passed-in-register-but-a-unique-ptrt-cannot](https://stackoverflow.com/questions/58339165/why-can-a-t-be-passed-in-register-but-a-unique-ptrt-cannot) – Jarod42 Jul 23 '23 at 13:53
  • Thanks, Jarod42! This actually answers my question. It originally concerned passing a `unique_ptr` *into* a function rather than returning it, but it becomes clear from the text that the reasons are the same for a return value. Bottom line: It is the nontrivial constructor/destructor that prevents passing parameters in registers. – sh- Jul 23 '23 at 15:38
  • See also: https://libcxx.llvm.org/DesignDocs/UniquePtrTrivialAbi.html – Artyer Jul 23 '23 at 17:04

0 Answers0