Chinese Yellow Pages | Classifieds | Knowledge | Tax | IME

In controlled circumstances you can pass the shared pointer by constant reference. Be sure that nobody is concurrently deleting the object, though this shouldn’t be too hard if you’re careful about to whom you give references.

In general, you should pass the shared pointer as a straight copy. This gives it its intended semantics: Every scope that contains a copy of the shared pointer keeps the object alive by virtue of its “share” in the ownership.

The only reason not to always pass by value is that copying a shared pointer comes at a certain price on account of the atomic reference count update; however, this might not be a major concern.


That depends on what you want. Should the callee share ownership of the object? Then it needs its own copy of the shared_ptr. So pass it by value.

If a function simply needs to access an object owned by the caller, go ahead and pass by (const) reference, to avoid the overhead of copying the shared_ptr.

The best practice in C++ is always to have clearly defined ownership semantics for your objects. There is no universal “always do this” to replace actual thought.

If you always pass shared pointers by value, it gets costly (because they’re a lot more expensive to copy than a raw pointer). If you never do it, then there’s no point in using a shared pointer in the first place.

Copy the shared pointer when a new function or object needs to share ownership of the pointee

Leave a Reply

Your email address will not be published. Required fields are marked *