patterncppCritical
Should we pass a shared_ptr by reference or by value?
Viewed 0 times
shouldshared_ptrvaluereferencepass
Problem
When a function takes a
-
by const reference:
-
or by value:
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.
shared_ptr (from boost or C++11 STL), are you passing it:-
by const reference:
void foo(const shared_ptr& p)-
or by value:
void foo(shared_ptr 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.
Solution
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
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.
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.
Context
Stack Overflow Q#3310737, score: 307
Revisions (0)
No revisions yet.