Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr to this
From: Jens Weller (JensWeller_at_[hidden])
Date: 2013-09-09 18:02:36

Gesendet: Montag, 09. September 2013 um 23:05 Uhr

Von: "Gonzalo Garramuno" <ggarra13_at_[hidden]>
An: boost-users_at_[hidden]
Betreff: Re: [Boost-users] shared_ptr to this

Here's  a compilable version of the program that shows the crash due to the ref. count reaching 0 in the thread.

#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <time.h>

struct Data
    Data( void* p ) :
    ptr( p )

    boost::shared_ptr<void> ptr;

void threadA( Data* d )
    boost::shared_ptr<void> ptr( d->ptr );
    delete d;
    // use ptr

class A
   void init_thread()
     Data* data = new Data( this );
     boost::thread t( boost::bind( threadA, data ) );

     void sleep()
    timespec req;
    req.tv_sec = 3;
    req.tv_nsec = 0;
    nanosleep( &req, NULL );

int main()
   A a;

   return 0;

Not sure, but as you allocate a on the stack, the invocation of delete this will not really be a good idea.
But as far as I see, thats what the shared_ptr will do. There is a enable_shared_from_this base class, which I think you should take a look at:

Also for sleep think about using boost::this_thread::sleep.

kind regards,

Jens Weller

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at