I'm trying to create a class that keeps a cache of objects. The constructor will be private. Instances will be created with a static function which returns shared_ptrs. I want to use a deleter to remove the instance from the cache (a map) and it seems like I should be able to use a lambda but I cannot get it to work.
Here is what I have. I commented out the line that creates the lambda:
#include <iostream>
#include <cstdlib>
#include <map>
#include <memory>
class CachedThing
{
public:
CachedThing(int size) {m_size=size;}
int m_size;
static std::map<int, std::shared_ptr<CachedThing>> m_cache;
public:
static void DeleteFromCache(int size)
{
}
static std::shared_ptr<CachedThing> CreateFromCache(int size)
{
auto it = CachedThing::m_cache.find(size);
if (it != CachedThing::m_cache.end())
{
std::cout << "FOUND " << size << std::endl;
return it->second;
}
std::cout << "CREATE " << size << std::endl;
//auto CacheDeleter = [] (int size) {CachedThing::DeleteFromCache(size);};
auto f = std::make_shared<CachedThing>(size);
m_cache[size]=f;
return f;
}
};
std::map<int, std::shared_ptr<CachedThing>> CachedThing::m_cache {};
int main()
{
std::cout << "Here we go..." << std::endl;
{
auto f1 = CachedThing::CreateFromCache(18);
}
auto f3 = CachedThing::CreateFromCache(20);
auto f2 = CachedThing::CreateFromCache(18);
auto f4 = CachedThing::CreateFromCache(20);
auto f5 = CachedThing::CreateFromCache(20);
}