Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we pass a shared_ptr by reference or by value?

When a function takes a shared_ptr (from boost or C++11 STL), are you passing it:

  • by const reference: void foo(const shared_ptr<T>& p)

  • or by value: void foo(shared_ptr<T> p) ?

I would prefer the first method because I suspect it would be faster. But is this really worth it or are there any additional issues?

Could you please give the reasons for your choice or if the case, why you think it does not matter.

like image 983
Danvil Avatar asked Jul 22 '10 15:07

Danvil


People also ask

Is shared_ptr reference counting?

The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.

Should I pass smart pointer by reference?

It's ok to pass a smart pointer by reference, except if it's to a constructor. In a constructor, it's possible to store a reference to the original object, which violates the contract of the smart pointers. You would likely get memory corruption if you did that.

When should you use shared_ptr?

An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted. So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object.

In what situation is a shared_ptr more appropriate than a Unique_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.


1 Answers

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

like image 186
mloskot Avatar answered Sep 19 '22 15:09

mloskot