Home > Article > Backend Development > Should I Pass `shared_ptr` by Value or by Reference?
Passing Shared Pointers: By Reference or By Value
When passing a shared_ptr (from boost or C 11 STL) to a function, the choice between passing it by const reference (void foo(const shared_ptr
Traditionally, it was believed that passing by reference would be faster as it avoids unnecessary copy operations. However, as discussed by experts at C and Beyond 2011 (Scott, Andrei, and Herb), this is no longer the case.
Should You Pass by Value or by Reference?
Unless there is an explicit need to share ownership of an object (such as between data structures or threads), there is no compelling reason to pass a shared_ptr by value. Passing by const reference is preferred for the following reasons:
When to Pass by Value
The only time it is advisable to pass a shared_ptr by value is when the intention is to transfer ownership of the object to the function. This is typically the case when the function needs to take responsibility for managing the object's lifetime.
Additional Considerations
For optimal performance, it is important to consider whether the shared_ptr can be move-optimized. As explained by Scott Meyers, move-optimization can eliminate the need for unnecessary copy operations. However, this optimization is only available in certain versions of C .
The above is the detailed content of Should I Pass `shared_ptr` by Value or by Reference?. For more information, please follow other related articles on the PHP Chinese website!