I have the following class used to access global registry variables.
template <typename T> using RegistryMap = std::unordered_map <std::string, T *>;
template <typename T> class Registry {
static RegistryMap<T> registry;
public:
static T* get(const std::string& name) {
auto it = registry.find(name);
return it == registry.end() ? nullptr : it->second;
}
static const RegistryMap<T>& getAll() {
return registry;
}
static bool add(const std::string &name, T *object) {
T* &store = registry[name];
if (store)
return false;
else {
store = object;
return true;
}
}
};
template <typename T>
RegistryMap<T> Registry<T>::registry = RegistryMap<T>();
I find that calls to the getAll method return different memory addresses, and I think my understanding of static members and object construction is faulty. I had thought that by declaring registry as static, each Registry template class would allocate memory for a RegistryMap, which would just be a pointer to the STL container on the heap. If I saved a reference to the map (the return value of getAll), I could refer to the STL container even after it gets modified.
Instead, getAll returns a reference of the current state of the map, but as things are added/deleted from the RegistryMap, getAll returns new addresses (specifically, old saved references of the map do not show the additional values.
Why would this be?
Edit:
auto t1 = Registry<void>::getAll();
Registry<void>::add("TESTING", nullptr);
auto t2 = Registry<void>::getAll();
Stepped through the preceding test in VS2013 debugger. t1 has size 0. t2 has size 1 and I can see ("TESTING", nullptr) inside.