|
Boost Users : |
Subject: Re: [Boost-users] shared_ptr to this
From: Steffen Heil (Mailinglisten) (lists_at_[hidden])
Date: 2013-09-10 11:41:44
Hi
In your case a is a stack variable that should never be deleted.
You should never use a shared_ptr for that.
Let's assume, your local variable a was only for showing the problem, but in fact your real code only uses heap allocated objects...
Then you should NOT pass a void* to the constructor of Data but a shared_ptr<void>.
The caller would then keep that shared_ptr around until it's own calls to the object are done...
See modified code below.
Regards,
Steffen
> #include <boost/bind.hpp>
> #include <boost/thread/thread.hpp>
> #include <time.h>
>
>
> struct Data
> {
> Data( boost::shared_ptr<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 boost::enable_shared_from_this<void>
> {
> public:
> void init_thread()
> {
> Data* data = new Data( shared_from_this<void>() );
> 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 = new A();
> boost::shared_ptr<void> x = a;
> a->init_thread();
> a->sleep();
> } // end of scope of x
> return 0;
> }
>
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