I'm currently working on a SDL_Project that includes Timers. A SDL_Timer can have a callback function, and since my timer is located in a class this callbackfunction is a static member function to which I pass "this" via void*-argument.
But the class has also another member variable, which is a pointer. But as soon as I call the callbackfunction, these pointers aren't valid anymore. Which kinda makes sense, I suppose, since the static function is called in another thread.
Is there a way to get around this problem? I'm not very familiar with Multithreading, so I have no idea what to look for.
This is a basic representation of what I'm doing, though this examples works just fine, since it's all in one thread, if my theory is right.
//A is just an interface so that B can hold a pointer to it
class A
{
public:
virtual int get() = 0;
};
class C
{
public:
C(){};
C(A* parent_arg)
{
parent = parent_arg;
}
void (*fptr)(C* sender) = nullptr;
static void callback(void* param)
{
//In my actual program, me has lost its parent pointer
C* me = (C*)param;
me->fptr(me);
};
//In my actual code, this function is from a SDL_Timer and
//runs in another thread
void Go()
{
callback(this);
}
A* parent = nullptr;
};
class B : A
{
public:
B()
{
c.parent = this;
};
virtual int get() { return myint; };
C c;
private:
int myint = 5;
};
void myfun (C* sender)
{
std::cout << sender->parent->get() << "\n";
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
b.c.fptr = myfun;
b.c.Go();
int test;
std::cin >> test;
return 0;
}
Edit:
Here is a little more information about what I do with C and B after they're created and how they are implemented in the actual program. All of the classes involved are copy constructable. And the member variable c in B is in a boost::stable_vector. Since for other tasks this all works fine, I assume that my copy constructors and assignment operators are ok. If I check the values of me in the callback, it turns out that me itself has still all its values in place, except the pointers.
Edit2:
I found the problem. I didn't update the parent pointer when I copied B object. Thank you all for your help.