Boost logo

Boost :

Subject: Re: [boost] [shared_ptr] calling functions by reference
From: Lars Viklund (zao_at_[hidden])
Date: 2011-05-29 00:09:48

On Sat, May 28, 2011 at 10:36:47PM -0400, Sid Sacek wrote:
> This might be a unimportant question and may have already been answered many times before, but I was wondering about functions that take shared pointers as arguments. Is there ever a reason I would not want to use a shared_ptr reference as an argument? I can't think of any, but is there any?
> class XYZ;
> void foo( shared_ptr< XYZ > &xyz )
> {
> }

Concurrent access to different shared_ptr instances in the same family
(sourced from the same source) is safe.
Concurrent access to a single shared_ptr instance is generally unsafe.

Passing the shared_ptr by reference puts the onus on you to ensure that
the shared_ptr instance you pass in is valid for the duration of the
function call, which is non-trivial in general.

Examples of the above would be foo(some_global_ptr); or foo(bar->baz);
where some_global_ptr is destroyed somewhere deep in the call chain, or
bar is destroyed during the call sequence.

I've had real-life bugs of this kind. It's not pretty. Unless you have a
genuine reason to access the same instance, try to avoid passing it by
reference-to-non-const. If you feel you need to avoid the non-free
copying cost, pass it by reference-to-const.

Lars Viklund | zao_at_[hidden]

Boost list run by bdawes at, gregod at, cpdaniel at, john at