I\'ve been reading quite a number of discussions about performance issues when smart pointers are involved in an application. One of the frequent recommendations is to pass a sm
First of all, don't pass a shared_ptr
down a call chain unless there is a possibility that one of the called functions will store a copy of it. Pass a reference to the referred object, or a raw pointer to that object, or possibly a box, depending on whether it can be optional or not.
But when you do pass a shared_ptr
, then preferably pass it by reference to const
, because copying a shared_ptr
has additional overhead. The copying must update the shared reference count, and this update must be thread safe. Hence there is a little inefficiency that can be (safely) avoided.
Regarding
” the price is making the code less safe, right?
No. The price is an extra indirection in naïvely generated machine code, but the compiler manages that. So it's all about just avoiding a minor but totally needless overhead that the compiler can't optimize away for you, unless it's super-smart.
As David Schwarz exemplified in his answer, when you pass by reference to const
the aliasing problem, where the function you call in turn changes or calls a function that changes the original object, is possible. And by Murphy's law it will happen at the most inconvenient time, at maximum cost, and with the most convoluted impenetrable code. But this is so regardless of whether the argument is a string
or a shared_ptr
or whatever. Happily it's a very rare problem. But do keep it in mind, also for passing shared_ptr
instances.