|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-12-29 15:41:25
Bronek Kozicki wrote:
> I need to be able to assign auto_ptr from shared_ptr. Here's
> simplified sample use:
>
> class M {
> boost::shared_ptr<int> ptr1_;
> boost::shared_ptr<int> ptr2_;
> public:
> M() : ptr1_ (boost::shared_ptr<int> (new int))
> {}
>
> void f()
> {
> ptr2_ = ptr1;
> // both ptr1 and ptr2 have use count = 2
> }
>
> std::auto_ptr<int> source()
> {
> std::auto_ptr<int> ptr3 = ptr1_.release();
> // ptr3 is now the only owner of pointer previously contained in ptr1_
> // both ptr1_ and ptr2_ have use count = 0 and contain null pointer
> // so their end-of-life will not destroy pointed object, and
> // end-of-life of ptr3 will not leave ptr1_ and ptr2_ with bad pointer
> return ptr3;
> }
> };
This effectively turns a shared_ptr into a weak_ptr, i.e. a pointer that can
be invalidated at any time. It is possible to use it, but I'd be very
reluctant to introduce the dreaded undefined behavior that cannot be
defended against, f.ex. in *p. You can't just test p first as another thread
can release() it after the test and before the dereference.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk