I'm implementing the factory pattern for component creation and want to implement a singleton container for all instances of each type created by the factory. Ideally this would be one vector for each type created in the factory.
This would be really easy if I could keep base class pointers in the vector, but alas my use case would vastly prefer all the instances be stored contiguously instead of wherever new puts them to get as many cache hits as possible.
I was thinking about doing something like this for the factory map:
Map<string,pair<constructorFnPtr, vector<baseClass>>
This has the issue of losing the data from the derived class as it is cast to the base class.
I was also thinking that a pointer to a vector as the second member of the pair would be a good way to do it, but I'm not sure how that could be implemented while still having a different data type stored in each vector. I don't think this would be possible since the templated vectors are all technically different classes.
Is there any way to do what I'm trying to do? I've been trying to figure something out for the past couple days with no luck.
Alternatively if there is another good way to store the vectors (ie as a static member of the component class) I'm open to any suggestions like that as well!
You can't do this with a std::vector of contiguous objects.
The reason is: a factory is supposed to build objects, and then return a pointer to them. The problem is that the pointer is going to be stored around in your application, while the next call to
your_vector.push_back()
is likely going to invalidate them, as the C++ documentation says:So, your next call to the factory can invalidate all your previous calls.