In our application we have an object that receives attributes at runtime. For example, to add a float to the object:
my_object->f("volume") = 1.0f;
Retrieving the volume works the same way:
cout << my_object->f("volume") << endl;
Internally, this is represented by a map of strings to their respective type. Each type has its own access methods and map. It looks like this:
map<string, float> my_floats;
map<string, int> my_ints;
map<string, void *> my_void_pointers;
Oh, the dreaded void *. Sometimes we need to add classes or functions to the object. Rather than have a separate map for every conceivable type, we settled on a void * map. The problem we’re having is with cleanup. Currently, we keep around a list of each type of these “dangling” objects that the void * point to, and call a cleanup function on these separate lists when necessary.
I don’t like having to use void * and all the extra attention it requires for proper cleanup. Is there some better way to store arbitrary types in an object at runtime, accessible via a string map, and still benefit from automatic cleanup via destructor?
This post seems to be a good answer to your question.
Storing a list of arbitrary objects in C++