An interface limitation forces me to cast MyObject*
into a void*
using static_cast. When getting this pointer back on later interface calls, I have to perform another static_cast from void*
to MyObject*
, because dynamic_cast wouldn't work in this case (explained here).
However, I'd like to perform a type-safety check, to ensure no weird things happen if somebody else changes parts of the code. If there is any check that can be performed under this circumstands, which one would be the best/most convenient one?
No, once you hit void*
it's all up to the code to get casts right. The root cause is that the void*
you get back theoretically can point to almost anything: a char
, int
, std::string
, std::complex<double>
, std::map<int, int>::iterator
and of course MyObject
.
The problem you'll face is that your cast will only work if the void*
actually points to a MyObject
, but in that case the cast wasn't necessary anyway.
A non-casting workaround is to keep a std::unordered_set<void*>
of all the void*
you created by casting MyObject*
, removing expired pointers via ~MyObject()
, and checking that set before casting.