Boost logo

Boost Users :

From: ostware (ostware_at_[hidden])
Date: 2003-05-13 16:53:14


(This message is also posted on sourceforge. Please forgive the double
posting, but I am still unfamiliar with the community...)

version: boost 1.30.0
library: smart pointers

I am using the boost::enable_shared_from_this base class from the
smart pointer library to implement shared_from_this in my classes. I
was amazed to find this class, after hours of thashing trying even to
figure out the very problem it solves. So, first off, thanks to the
boosters.

My problem is that shared_from_this() throws boost::bad_weak_ptr if
called from my class's destructor. Is this a design decision? a bug?
am I misreading a class requirement?

The problem (if it is one...) is that sp_counted_base::release()
decrements use_count_ before calling dispose(). Then when my class
calls shared_from_this from its destructor (via dispose()),
sp_counted_base::add_ref fails (use_count == 0) and throws
boost::bad_weak_ptr.

I would suggest either setting use_count_ after dispose(), or
clarifying in the docs that shared_from_this can't be called from a
destructor. (... which would send me back to the drawing board to
solve my problem)

It would also be handy to have an exception less version of
share_from_this which justs returns a null shared_ptr.

Thanks for any help. ... Michael Ost

Something like this (warning: uncompiled, untested!) ...

class T : public enable_shared_from_this {
public:
   T() {}
   ~T()
   {
      shared_ptr<T> ptr = shared_from_this();
      // trouble: exception, can't get a shared_ptr
   }
};

main()
{
   shared_ptr<T> ptr = shared_ptr(new T());
   ptr.reset();
}


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