I implemented a simple ResourceManager - everything was fine until I tried to implement its destructor for (emergency) clean up(for example in case of fatal exception). I was not able to find a single way to do it:
template<typename T>
class ResourceManager
{
public:
std::unordered_map<std::string, std::weak_ptr<T> > resource_map;
std::shared_ptr<T> getResource(std::string name)
{
std::shared_ptr<T> res = resource_map[name].lock();
if(!res)
{
res = std::shared_ptr<T>(new T(this, name));
resource_map[name] = res;
}
return std::move(res);
}
void Release(std::string name)
{
resource_map.erase(name);
};
~ResourceManager(void) { /* ???? */}
};
class Texture
{
private:
ResourceManager<Texture> * manager_;
std::string name_;
public:
Texture(ResourceManager<Texture> * manager, std::string& name)
: manager_(manager), name_(name) { }
~Texture(void){
manager_->Release(name_);
}
};
Obviously, I have to iterate over all active resources...but how can I free them if the ResourceManager is not technically (sole)owner of the resources? This might be flaw of design, if that is the case please suggest alternative.
EDIT: in response to answers, to define "resource manager" I imagine authoritative cache - storage for references to resources that can look up resources(=no duplicates) and manages their state in memory (in-memory, description-only(=path+type) and freed), all above as automated as possible. (there should be separate ResourceLoaders, but that does not change much for this question)