
Peter Dimov wrote:
Is there a common sense about how a shared_ptr<> should be passed to functions/methods: by-value or by-(const-)reference?
1) void test(boost::shared_ptr<A> a); 2) void test(boost::shared_ptr<A>& const a);
You should pass by value. Passing a shared_ptr means giving the opportunity to the callee to use the data without worrying about its lifetime. Would you pass it by ref, the callee won't own the the pointee and hence cannot use it reliabily (it may get deleted behind its back). By passing it by value, the callee makes a copy of the shared_ptr, hence incrementing the ref count. The pointer won't get deleted while the callee use the pointer. Hope it makes sense.
I'm not 100% sure that such a scenario (the pointer gets deleted behind its back if the shared_ptr is passed by ref) is technically possible, but I agree that logically it's better to pass by value.
It is possible. In a multithreaded program, another thread may reset() a. In a single-threaded program, a function called by test() may reset a. I have encountered it myself.
But doesn't that violate the thread-safety guarantee of the shared_ptr interface anyway? Using two different shared pointers to the same object is guaranteed to be thread safe, but you aren't supposed to let a thread modify a particular shared pointer instance while another thread is accessing it. The fact that it is passed by const reference in a function call is a red herring, since the multiple access violation can occur before or after the call too. -- Jon Biggar Levanta jon@levanta.com