Boost logo

Boost Users :

From: Andrew Holden (aholden_at_[hidden])
Date: 2007-12-19 10:02:09


STenyaK (Bruno Gonzalez) [stenyak_at_[hidden]] wrote:
> Ok. This is how my code structure looks:
> ----------------------------
> typedef shared_ptr<MyClass> pMyClass;
> void* MyClass::actionThread(void *objectPointer) {
> pMyClass * _obj = static_cast<pMyClass*>(objectPointer);
> pMyClass obj = *_obj;
> obj->action(false);
> delete _obj;
> }
> void MyClass::action(bool threaded)
> {
> if (threaded)
> {
> pthread_t tid;
> pthread_create(&tid, 0, actionThread, new pMyClass(this))
> } else {
           //TODO: actually perform the action
> }
> }
> ----------------------------
> When calling an instance->action(false) it works correctly.
> When calling instance->action(true) it sometimes segfaults.
> So i'm not sure i interpreted your code sample correctly.
>
> Do i need to use enable_shared_from_this?
> Or do i have to avoid using "this" (orig_ptr in your code) somehow
> maybe?
>
> Thanks in advance!

I would stongly recommend shared_from_this. You code, as written, will
guaranteee that actionThread will destroy the MyClass as soon
asactionThread finishes, even if the main thread still expects it to
exist. This would result in a double-free if the main thread has its
own shared pointer to the object.

Actually, the fact that this is a member function opens another
possibility. First, derive MyClass from enable_shared_from_this
<MyClass>, then you can implement the functions like this:

----------------------------
typedef shared_ptr<MyClass> pMyClass;
void* MyClass::actionThread(void *objectPointer)
{
    MyClass * _obj = static_cast<MyClass*>(objectPointer);
    pMyClass obj = _obj->shared_from_this();
    obj->action(false);
}

void MyClass::action(bool threaded)
{
    if (threaded)
    {
        pthread_t tid;
        pthread_create(&tid, 0, actionThread, this)
    } else {
        //TODO: actually perform the action
    }
}
----------------------------

This works because shared_from_this is specifically designed to allow
member functions of a class to recover the shared pointer to the object.


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