Boost Users :
From: Yuval Ronen (ronen_yuval_at_[hidden])
Date: 2005-01-21 08:15:56
>>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.
And I would like to add another thing. You should consider what are the
requirements of the function. If it wants to be one of the shared owners
of the pointer, then it should get a shared_ptr by value. On the other
hand, if the function doesn't care about ownership, and only needs an
object, then it should get a simple pointer ot reference (either const
or not) to the object, like a "regular" function.
Elaboration: When we look at a "regular" function 'void f([const] T &)',
it looks obvious to us that f() requires the caller to supply a T
object, and guarantee that it stays alive during the execution of f().
So if this is what you want, use this semantics and not shared_ptr.
Hope my opinion was useful to anyone.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net