Search code examples
c++c++11shared-ptr

How to pass a std::shared_ptr<Resource> to a function?


Possible Duplicate:
Should I pass a shared_ptr by reference?
Passing smart pointers as arguments

Should I pass it by value or by constant reference? I have read numerous rules of thumb on whether to pass a copy constructible object by value or by constant reference. Such as:

  1. pass objects by constant reference and built in types by value (except function objects)
  2. pass by value unless size of the object (including dynamic memory) is less than 2 * size of a double.

Could you explain how do these rules apply to std::shared_ptr<Resource>? I understand that the object is probably very small, likely a pointer and a reference counter, but it is still an object. What is the best practice here?


Solution

  • Perhaps the most important concern (with regards to performance) is that creating a copy of a std::shared_ptr<...> (such as happens when you pass by value) requires an interlocked increment of a reference count. Or maybe some other form of synchronization like a critical section, depending on implementation. Such a cost could be significant in a multithreaded program.

    Passing by reference is almost certain to be a better choice. It's main drawback (or is this only with boost::shared_ptr<...>?) is that shared_ptr<...> offers only the standard thread safety guarantee: access to a single shared_ptr<...> must be guarded (e.g. by a mutex) unless all accesses are only to const methods. In a multithreaded situation, passing around const references to shared_ptr<...>s may make it more difficult to ensure proper synchronization.

    In a single threaded program, it probably doesn't make much of a difference.