Boost logo

Boost Users :

From: Paul (elegant_dice_at_[hidden])
Date: 2005-01-23 17:54:17


> I think multithreading is red herring. It just a problem with passing by
> reference (and multithreading just adds to the possibility of this to
> happend):
>
> shared_ptr<A> a;
>
> void load() { a = new A; }
> void unload() { a.reset(); }
>
> void foo() { unload(); }
>
> void process( shared_ptr<A> const& a )
> {
> .... // here a is valid
> foo(); // this function may as well be called from other thread
> .... // here a is invalid
> }
>
> int main()
> {
> load();
> process( a );
> unload();
> }
>

I don't understand where the multithreading is in this program, however
it should not pose a problem when passing to a function as a reference.

In this case, the callstack looks like
foo()
process()
main() <-- a's handle is held here

Theres no need to keep the shared_ptr as a value except when you need to
store it post-function call.

eg:

struct whatever
{
   shared_ptr<X> storage; <-- must be value
   whatever( shared_ptr<X>& x ) : storage(x) {} <-- ok to pass by ref
   void do_stuff() { storage->exec(); } <-- if not stored as value,
might be hanging ref
};

void main()
{
   shared_ptr<X> thenew = make_new();
   whatever stuff(thenew); <-- ptr remains valid until call returns
   thenew.reset(); <-- if not stored as value then storage now invalid
   stuff.do_stuff(); <-- call and use stored ptr.
}

so, store shared_ptrs as value, pass as reference/const-ref.

Paul


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