Skip to content

Instantly share code, notes, and snippets.

@Shtille
Created February 4, 2025 12:15
Show Gist options
  • Save Shtille/672f76dff95697ea0ce22faf04f19b80 to your computer and use it in GitHub Desktop.
Save Shtille/672f76dff95697ea0ce22faf04f19b80 to your computer and use it in GitHub Desktop.
Cache for data to be shared between different instances
#include <map>
#include <memory>
template <class Key, class Data>
class DataCache
{
public:
template<typename... Args>
std::shared_ptr<Data> GetData(const Key& key, Args... args)
{
auto it = map_.find(key);
if (it != map_.end())
if (auto data = it->second.lock())
return data;
auto data = std::make_shared<Data>(args...);
map_[key] = data;
return data;
}
private:
std::map<Key, std::weak_ptr<Data> > map_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment