In a complex code base, I have an array of pointers of a non-virtual base class (the base class has no virtual methods)
Consider this code:
Output (compiled from Mingw-w64 GCC 4.9.2 on Win64):
Data = 0 Data = 1 Data = 2 Data = 0 Data = 1 Data = 4771632
The reason for the failure is that each instance of TVirtualDerived has a pointer to a virtual table that is not in TBase. Thus, bringing to TBase without information of the previous type (from void * to TBase *) is unsafe.
The thing is, I cannot avoid casting in void * in the first place. Adding a virtual method (destructor, for example) to the base class works, but at a cost of memory (which I want to avoid)
Context:
we implement a signal / slot system in a very limited environment (memory is very limited). Since we have several million objects that can send or receive signals, such optimization is effective (when it works, of course)
Question:
How can I solve this problem? So far I have found:
1 - add a virtual method to TBase. It works, but actually it does not solve the problem, it avoids it. And it is inefficient (too much memory)
2 - casting in TBase * instead of casting in void * in the array, due to loss of generality. (maybe I'll try next)
Do you see another solution?
source share