【folly】EvictingCacheMap用法

 

 

#include <folly/EvictingCacheMap.h>
#include <iostream>

class CacheMgr {
public:
    CacheMgr(size_t cap): cache_(
              cap,
              // 淘汰回调函数(在构造函数初始化列表中)
              [](const int& key, const std::string& value) {
                  std::cout << "[Evicted] key=" << key
                            << ", value=" << value << std::endl;
              }) {
        // 你也可以在这里做其他初始化
        std::cout << "CacheMgr constructed, capacity=" << cap << std::endl;
    }

    // 写入缓存
    void put(int key, const std::string& value) {
        cache_.set(key, value);
    }

    // 查询
    bool get(int key, std::string& out) {
        if (auto* v = cache_.get(key)) {
            out = *v;
            return true;
        }
        return false;
    }

private:
    // 成员变量:EvictingCacheMap
    folly::EvictingCacheMap<int, std::string> cache_;
};

int main() {
    CacheMgr mgr(3);

    mgr.put(1, "A");
    mgr.put(2, "B");
    mgr.put(3, "C");

    std::string val;
    mgr.get(2, val);  // 访问一下 key=2,使其最近使用

    mgr.put(4, "D");  // 容量满,自动淘汰最旧的 key=1

    return 0;
}

 

posted @ 2025-12-09 10:44  苏格拉底的落泪  阅读(0)  评论(0)    收藏  举报