Created
September 2, 2016 21:36
-
-
Save stmoerman/b21dad06985efd808e7d5558e981bac9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
#include <map> | |
template<typename Key, typename Value> | |
class WeakCache { | |
public: | |
template<typename... Args> | |
WeakCache(Args&&... args) | |
: cache_(std::forward<Args>(args)...) {} | |
std::shared_ptr<Value> operator[] (const Key& key) { | |
auto& value = cache_[key]; | |
auto ptr = value.lock(); | |
if(ptr) | |
return ptr; | |
value = ptr = std::make_shared<Value>(key); | |
return ptr; | |
} | |
private: | |
std::map<Key, std::weak_ptr<Value>> cache_; | |
}; | |
This acts as a cache of objects that will create the object when you request it, | |
or if the object already exists (and hasn't been deleted), will return the existing object. | |
Good for immutable objects coming from resources files. For example, | |
in my usage I had an immutable Dictionary object which had a set of built in word list configurations, | |
expressed as a Dictionary::Config enum. To create an dictionary, one could simply call Dictionary::Create(config), | |
which looks like: | |
shared_ptr<Dictionary> Dictionary::Create(Config config) { | |
return dictionaryCache[config]; | |
} | |
If the dictionary object already exists and hasn't been deleted, you get it. Otherwise, the dictionary would get created anew. This was particularly good because dictionaries are expensive to read in and setup. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment