Does somebody have any idead on how to pass boost::shared_ptr – by value or by reference.
On my platform (32bit) sizeof(shared_ptr) equals 8 bytes and it looks like I should pass them by reference, but maybe somebody has another opinion / did a profile / something like that?
You can see this in two ways:
a
boost::shared_ptris an object (and should be passed by const &).a
boost::shared_ptrmodels a pointer and should be treated as a pointer.Both of them are valid, and the second option will incur the cost of constructing and destructing the additional instance (which shouldn’t be a big issue unless you’re writing performance-critical code).
There are two cases when you should pass by value:
when you’re not sure that the type of the pointer will remain the same. That is, if you are considering replacing the
shared_ptr<T>withT*in your codebase somewhere in the future, it makes sense to writetypedef shared_ptr<T> TPtr;and define your functions asvoid yourfunction(TPtr value)In this case, when you change the pointer type you will only have to modify the
typedefline.when you are sharing a pointer between two modules with a different lifetime. In that case, you need to make sure you have two instances of the smart pointer, and that both increment the reference count of the pointer.
In other cases, it’s a matter of preference (unless you’re writing performance-critical code in which case different rules apply).