LRU Cache with a static variable for garbage value I have tried to implement a Least Recently Used cache with only C++ STL containers. The main thing that I keep asking my self the static variable called garbage_val. Is it a good practice to have such a static variable just for garbage values? 

template&lt;typename Key, typename Value&gt;
class LRU_Cache
{
struct Node
{
    Key k;
    Value v;
};

public:
static Value garbage_val;

LRU_Cache(unsigned int capacity)
{
    capacity_ = capacity;
}

Value get(Key key)
{
    auto node = cache_.find(key);

    if(node == cache_.end())
    {
        return garbage_val;
    }

    Value val = (*(node-&gt;second)).v;
    recentlyList_.erase(node-&gt;second);

    Node n; n.v = val; n.k = key;

    recentlyList_.push_back(n);
    cache_[key] = --recentlyList_.end();

    return val;
}

void set(Key key, Value val)
{
    auto node = cache_.find(key);

    if(node != cache_.end())
    {
        recentlyList_.erase(node-&gt;second);
    }
    else
    {
        evict_if_needed();
    }

    Node n; n.v = val; n.k = key;
    recentlyList_.push_back(n);
    cache_[key] = --recentlyList_.end();
}

void evict_if_needed()
{
    if(cache_.size() &gt;= capacity_)
    {
        auto node = cache_.find(recentlyList_.begin()-&gt;k);
        recentlyList_.pop_front();
        cache_.erase(node);
    }
}

virtual ~LRU_Cache(void)
{
}

void print()
{
    std::cout &lt;&lt; "Objects in Memory:" &lt;&lt; std::endl;
    for(auto&amp; c : cache_)
    {
        std::cout &lt;&lt; "(" &lt;&lt; c.first &lt;&lt; "," &lt;&lt; (*(c.second)).v &lt;&lt; ")" &lt;&lt; std::endl;
    }

    std::cout &lt;&lt; "Recently used:" &lt;&lt; std::endl;
    for(auto&amp; r : recentlyList_)
    {
        std::cout &lt;&lt; "(" &lt;&lt; r.k &lt;&lt; "," &lt;&lt; r.v &lt;&lt; ")" &lt;&lt; std::endl;
    }
}
private:
LRU_Cache(void){}

std::unordered_map&lt;Key, typename std::list&lt;Node&gt;::iterator&gt; cache_;
std::list&lt;Node&gt; recentlyList_;
unsigned int capacity_;
};
template&lt;typename Key,typename Value&gt; Value LRU_Cache&lt;Key,Value&gt; ::garbage_val;
Is it a good practice to have such a static variable just for garbage values?


Maybe not:


garbage_val is a Value, so if you return it, then the caller doesn't know whether the get succeeded.
If garbage_val is supposed to be a magic number (an impossible Value), different users of the class might want different magic numbers ... so why isn't garbage_val an instance member instead of a static member?
Normally container classes expect the caller to check that iterator != end() before dereferencing the iterator.


Instead, the following methods might be appropriate:

// throws an exception if key does exist.
Value get(Key key) { ... }
// tests whether key exists: use this before calling get.
bool contains(Key key) { ... }
// return true and initializes value iff key exists.
// if key doesn't exist then valueOut is not initialized. 
bool tryGet(Key key, Value&amp; valueOut) { ... }