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
{
   public:
   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;
   a.init_thread();
   a.sleep();

   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:
http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/enable_shared_from_this.html

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

kind regards,

Jens Weller
 


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