Boost logo

Boost :

Subject: Re: [boost] [shared_ptr] calling functions by reference
From: Sid Sacek (ssacek_at_[hidden])
Date: 2011-05-29 00:18:05


-----Original Message-----
From: boost-bounces_at_[hidden] [mailto:boost-bounces_at_[hidden]] On Behalf Of Matt Calabrese
Sent: Saturday, May 28, 2011 10:53 PM
To: boost_at_[hidden]
Subject: Re: [boost] [shared_ptr] calling functions by reference

> One common reason given to pass by value is to implicitly handle the case
> where you call a separate function which may release your shared pointer as
> a side effect. For instance:
>
> //////////
> shared_ptr< int > a( new int( 2 ) );
>
> void foo() { a.reset(); }
>
> void bar( shared_ptr< int > const& arg )
> {
> foo(); *arg = 0; // Kaboom
> }
>
> int main() { bar( a ); }
>

I agree with you that your example above will crash the program, but calling Reset() is micro-managing the smart-pointer. There should be no good reason to call reset on a regular basis, and only have objects go out of scope. That is my understanding of the point of the shared_ptr<>.

Let's assume that reset is never used, and shared_ptr<> is not set to a global variable, then the only thing that comes to my mind is that there might be a multi-threading subtlety that I'm not aware of.

For example, suppose thread-A created an object and passed it to thread-B, which then calls Foo(shared_ptr<>&). I started to think about what happens when the original thread-A releases its pointer while function Foo() is still running inside thread-B. However, there seems to be no way that the shared_ptr<> object can be passed from one thread to another without making a copy of the shared_ptr<>. That means each thread owns its own copy of the shared_ptr<>, thereby preventing any multi-threading issues from happening.

During an application shutdown, the master thread would communicate with all other threads to perform an orderly shutdown, and when all auxiliary threads have gone away, the master thread may want to call reset on some of these managed resources, but at this point, there is no possibility of threads stepping on each other.

This seems like a disciplined approach to using shared_ptr<> to me. I figured that with all of the experienced coders out there, that there may have been a very surprising subtlety that was not anticipated, but which ended up braking their program. This is the sort of information I'm seeking regarding shared_ptr<> references.

-Sid Sacek


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