STenyaK (Bruno Gonzalez) [stenyak@gmail.com] wrote:
Ok. This is how my code structure looks: ---------------------------- typedef shared_ptr<MyClass> pMyClass; void* MyClass::actionThread(void *objectPointer) { pMyClass * _obj = static_cast
(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