Boost logo

Boost Users :

From: Jason Winnebeck (yg-boost-users_at_[hidden])
Date: 2003-07-21 21:06:34


I just wanted to follow up on my previous thread about my issues I've
been discussing on the list with a general question. By default should
I try to use shared_ptr or weak_ptr? I had always thought that
shared_ptr should always be used except for rare cases where weak_ptr's
semantics is either very desirable or needed.

Now my pointers experience so far has been limited to explicit memory
management (new/delete) and in Java with its references, where any
reference keeps an object alive, and weak references exist but I've
never used them despite a few years of using Java on the job.

Based on some of the discussion (particularly from Mr Dimov), made me
think that weak_ptr may be desirable a lot more often than I previously
thought.

I know that shared_ptr, unlike Java, is suceptable to cycles. And I
feel that shared_ptr is better and less bug prone than new/delete but
I'm afraid I'll have cycle problems if I just start throwing shared_ptr
all over the place. I know that in my code I have back pointers all
over the place, which I thought was pretty common, but I have realized
that that only occurs when I'm following the generator/listener design
scheme, and I've gotten that figured out. So A to B, B to A cycles
don't concern me much but I do wonder about long cycles if I use
shared_ptr a lot. The rule of thumb I'm using right now is to look for
cycles if I "convert" a class to use shared_ptr (static crate method)
that contains shared_ptr objects, similar to the rule I use to check for
deadlocks with mutexes.

But with all of these rules checking for safety I begin to question
somewhat the benefits of shared_ptr over normal pointers. I suppose
with shared_ptr you can only leak memory whereas with normal pointers
you can do lots of nasty uninitialized accesses.

I can see an argument that using shared_ptr only when needed and
weak_ptr otherwise can help prevent cycles. But using weak_ptr requires
the code to handle both cases of the lock operation, and I'm still
unsure about any performance issues with lock if there is a mutex
involved -- although too slight to not choose weak_ptr, it is enough to
ask why not choose shared_ptr over weak_ptr if they both work equally well.

Thank you for your comments and patience with my attemps at understanding,

Jason Winnebeck


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