Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-01-21 09:16:03

Yuval Ronen 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.

If these cases are not a concern, pass by const ref is usually slightly more

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at