Reputation: 55
I had a problem while hacking a bigger project so I made a simpel test case. If I'm not omitting something, my test code works fine, but maybe it works accidentally so I wanted to show it to you and ask if there are any pitfalls in this approach.
I have an OutObj which has a member variable (pointer) InObj. InObj has a member function. I send the address of this member variable object (InObj) to a callback function as void*. The type of this object never changes so inside the callback I recast to its original type and call the aFunc member function in it. In this exampel it works as expected, but in the project I'm working on it doesn't. So I might be omitting something or maybe there is a pitfall here and this works accidentally. Any comments? Thanks a lot in advance.
(The problem I have in my original code is that InObj.data is garbage).
#include <stdio.h>
class InObj
{
public:
int data;
InObj(int argData);
void aFunc()
{
printf("Inside aFunc! data is: %d\n", data);
};
};
InObj::InObj(int argData)
{
data = argData;
}
class OutObj
{
public:
InObj* objPtr;
OutObj(int data);
~OutObj();
};
OutObj::OutObj(int data)
{
objPtr = new InObj(data);
}
OutObj::~OutObj()
{
delete objPtr;
}
void callback(void* context)
{
((InObj*)context)->aFunc();
}
int main ()
{
OutObj a(42);
callback((void*)a.objPtr);
}
Upvotes: 1
Views: 458
Reputation: 106530
What you have posted should be "safe" insofar as a non type safe operation like this can be safe. I would replace the casts you have though with static_cast
instead of C style casts, because static_cast
doesn't allow you to make such unsafe conversions between types. If you try to do something unsafe with static_cast
the compiler will tell you instead of leaving you guessing.
(Side unrelated note: InObj's constructor should use initialization rather than assignment:
InObj::InObj(int argData) : data(argData)
{
}
)
Upvotes: 0
Reputation: 355009
Yes, this is safe.
A pointer to any type can be converted to a pointer to void and back again.
Note that the conversion to void*
is implicit, so you don't need the cast.
Upvotes: 3