Boost logo

Boost :

Subject: Re: [boost] [shared_ptr] delete shared_ptr
From: Joshua Juran (jjuran_at_[hidden])
Date: 2011-03-17 08:14:56


On Mar 17, 2011, at 3:24 AM, Christoph Heindl wrote:

> On Thu, Mar 17, 2011 at 10:56 AM, Joshua Juran <jjuran_at_[hidden]>
> wrote:
>> Is there a reason to pass the shared_ptr by value instead of const
>> reference?
>
> I'm not sure. After reading several discussions on the web [1,2] I
> concluded that I'll stick with by-value.
>
> [1] http://stackoverflow.com/questions/327573/c-passing-references-to-boostshared-ptr
> [2] http://stackoverflow.com/questions/3310737/shared-ptr-by-reference-or-by-value

My understanding is that the arguments for pass-by-value boil down to:

(1) The called function might cause some side effect which includes
destroying the referenced object before using the object. This
doesn't apply in your case, since you're just constructing a copy.

(2) Another thread might destroy the object before the called function
uses it. This is a red herring: Either the calling function has its
own local copy, which will persist until the called function returns,
or it's using storage accessible to another thread, in which case it's
vulnerable -- but passing the shared_ptr by value to the called
function doesn't close that vulnerability. The same hypothetical
thread could either release the shared resource (reset()) or destroy
the storage for the shared_ptr itself before the function call
occurs. If this is in fact a risk (which it may well not be) then the
calling code needs to arrange serialized access and either store its
own local copy of the shared_ptr before passing it to another function
or maintain a lock for the duration of the function call.

One of the C++ best practices (from the book of the same name) is
avoiding premature pessimization.

Josh


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk