I'm writing code and until now I was using structures like this:
struct s{
enum Types { zero = 0, one, two };
unsigned int type;
void* data;
}
I needed some generic structure to store data from different classes and I wanted to use it in std::vector, so that's reason why I can't use templates. What's better option: unions or void pointers?
Void pointer allocates only as much space as I need, but c++ is strong typed language for some reason and casting everywhere I need to use those data is not the way c++ code should be designed. As I read, void pointers shouldn't be used unless there's no alternative.
That alternative could be Unions. They comes with c++ and uses the same memory space for every member, very much like void pointers. However they come at price - allocated space is the size of largest element in union, and in my case differences between sizes are big.
This is rather stylistic and "correct language using" problem, as both ways accomplish what I need to do, but I can't decide if nicely stylized c++ code can pay for that wasted memory (even though memory these days isn't a big concern).
See Question&Answers more detail:os