Opened 14 years ago

Closed 14 years ago

#147 closed Support Requests (Rejected)

shared_from_this fails in a destructor

Reported by: nobody Owned by: Peter Dimov
Milestone: Component: smart_ptr
Version: None Severity:
Keywords: Cc:


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
misunderstanding 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. 

It would also be handy to have an exception-less
version of share_from_this which justs returns a null
shared_ptr, kind of like how shared_ptr::get doesn't throw.

Thanks for any help. ... Michael Ost

PS: code looks something like this (warning:
uncompiled, untested!) ...

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

   shared_ptr<T> ptr = shared_ptr(new T());

Attachments (0)

Change History (2)

comment:1 Changed 14 years ago by murgatroid

Logged In: YES 

I submitted this as user murgatroid, email Somehow that didn't get recorded...?

comment:2 Changed 14 years ago by Peter Dimov

Status: assignedclosed
Logged In: YES 

This behavior is by design. Since the destructor will destroy 
the object, it is not safe to create a shared_ptr to it as it will 
become dangling once the destructor ends.

Modify Ticket

Change Properties
Set your email in Preferences
as closed The owner will remain Peter Dimov.
The resolution will be deleted.

Add Comment

E-mail address and name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.