Gesendet: Montag, 09. September 2013 um 23:05 Uhr
Von: "Gonzalo Garramuno"
An: boost-users@lists.boost.org
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
#include
#include
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....
Also for sleep think about using boost::this_thread::sleep.
kind regards,
Jens Weller