Passing Shared Pointers: By Reference or By Value
When invoking a function that accepts a shared pointer, developers face the choice between passing by const reference or by value. While passing by const reference may seem preferable for performance reasons, the decision warrants further consideration.
According to experts at the 2011 C and Beyond "Ask Us Anything" session, there is generally no advantage to passing a shared pointer by value. Passing by const reference is the recommended approach unless the intent is to share ownership of the object.
Why Pass by Const Reference?
Passing by const reference ensures that the shared pointer remains immutable within the function, preserving its value and preventing unintended modifications. This aligns with the intended behavior of a shared pointer, which symbolizes shared ownership of an object.
Why Not Pass by Value?
While passing by value may create a copy of the shared pointer, modern C compilers optimize away the unnecessary duplication of the underlying managed object. Passing by value only becomes beneficial when the shared pointer can be move-optimized, allowing the ownership of the managed object to be transferred to the function without copying. However, this optimization is contingent on the specific C version being used.
Additional Considerations
The 2012 GoingNative "Ask Us Anything" panel further elaborated on this topic. Key takeaway from the discussion include:
The above is the detailed content of Should I Pass Shared Pointers by Reference or by Value?. For more information, please follow other related articles on the PHP Chinese website!