30 秒面试回答
LRU 在容量不足时淘汰最久未使用的条目。常见实现用哈希表按键找到双向链表节点,命中就把节点移到头部,尾部保留淘汰候选。查找、更新和删除平均 O(1),哈希冲突下最坏可到 O(n)。C++ 实现还要保持两个容器一一对应:新链表节点建立后,哈希插入失败要删回该节点;全部准备成功才淘汰旧尾。命中会修改顺序,所以这个 get 也需要写同步。
核心概念
本文缓存固定为 int 键和 int 值,容量表示条目数。链表头是 MRU(最近使用),尾是 LRU(最久未使用)。get 命中、新键 put 和已有键更新都会把条目置于头部;查询缺失键不改变顺序。容量为零表示禁用存储,put 不保存数据。其他接口可以采用不同约定,但实现、测试和调用者必须使用同一份语义。
LRU 只用最近访问顺序决定淘汰。LFU 主要考虑访问频率,TTL 决定条目是否过期,数据版本则判断副本是否仍可使用。这些条件各有用途:刚被读取的旧配置仍可能失效,长时间未读的静态数据也未必过期。真实系统还可能采用近似策略;例如 Redis 的淘汰文档 说明其 LRU 通过采样选择候选,并不维护本文这样的全局精确顺序。
get 返回 optional<int>:无值表示未命中,有值表示一个独立整数副本。缓存内部节点被删除后,先前返回的值仍可使用。缓存不负责回源加载,也没有 TTL、持久化、并发控制或动态调整容量。
原理深入
两个容器要描述同一组条目
order_ 保存 (key, value),index_ 保存 key -> list::iterator。公开操作完成后,应满足:每个链表键唯一;索引恰好指向同键节点;两个容器大小相等且不超过容量。链表顺序还必须与已完成的访问历史相符,仅检查大小不能发现错误的淘汰候选。
以容量 2 为例,表中左侧是 MRU:
| 操作 | 返回值 | 链表顺序 | 解释 |
|---|---|---|---|
put(1, 10) | 无 | 1:10 | 新条目最近使用 |
put(2, 20) | 无 | 2:20, 1:10 | 缓存装满 |
get(1) | 10 | 1:10, 2:20 | 只调整命中节点 |
put(3, 30) | 无 | 3:30, 1:10 | 淘汰最久未用的键 2 |
put(1, 11) | 无 | 1:11, 3:30 | 更新已有键,不增加条目 |
命中后用同一链表的单元素 splice 把节点移到头部。节点及其迭代器保持有效,因此索引中保存的 list 迭代器无需改写。该操作在满足前置条件时不抛出且为常数复杂度,见 N4861 list.ops。
新增操作把淘汰放在最后
新键 put 先在链表头构造节点,再将它的迭代器插入哈希索引。第一步可能因分配失败而抛出;list 单元素插入 此时没有效果。第二步如果失败,catch 删除刚添加的头节点并重抛,恢复旧顺序。
这个证明依赖具体类型。demo 的键和值为 int,哈希与比较不抛出,析构和释放不抛出;标准整数 hash 的异常条件见 unord.hash。在这些前提下,哈希表单元素插入的分配异常没有效果,见 unord.req.except。如果允许哈希函数抛出,不能直接套用这条插入无效果保证。
两个容器都插入成功后,若超过容量,先删掉旧尾节点对应的哈希项,再弹出链表尾。淘汰阶段在本例的类型约束下不抛出,因而不再需要回滚。若先淘汰后分配新节点,分配失败就会让调用者失去原有条目。
因此强保证针对键值和最近使用顺序成立,但准备阶段会短暂存在 capacity + 1 个条目。这是条目上限在公开操作边界成立的实现,不能用于承诺任何时刻都不超出某个字节预算。
更新和删除也有顺序要求
更新已有键只赋值并调整节点位置。int 赋值不抛出;推广到任意值类型后,赋值可能改到一半再失败,返回值复制也可能引入异常路径。泛型缓存需要重新规定这些操作的保证。
删除先从索引找到 list 迭代器,然后删除索引项,最后销毁链表节点。这样不会留下指向已销毁节点的索引。demo 不执行用户回调,也不支持重入;如果加入淘汰通知,回调是否会抛出、是否再次访问缓存,都需要单独设计。
数据结构/系统内部实现
链表解决已知节点的重排,哈希表解决按键定位。标准保证的是操作语义与复杂度,节点字段布局、桶数组组织和哈希缓存方式由标准库实现决定。通常这两个容器都有节点及分配开销,不能把“双向链表加哈希”当作连续内存方案。
| 保存的对象 | 能否跨 index_ 的 rehash 使用 | 失效条件举例 |
|---|---|---|
unordered_map 迭代器 | 不能依赖仍有效 | rehash,或对应索引项被删 |
| 指向 map 元素的指针或引用 | rehash 不使其失效 | 对应索引项被删 |
索引中保存的 list::iterator | 可以,链表未被 rehash 操作修改 | 对应链表节点被删 |
| 指向缓存内部 value 的引用 | 本实现不向外提供 | 若提供,淘汰或删除该节点后失效 |
这些对象不能统称为“缓存迭代器”。无序容器要求 明确区分 rehash 对迭代器、指针和引用的影响。实现不保留 map 迭代器跨越可能扩容的 emplace;淘汰时从链表尾拿键,再查找并删除索引项。链表单节点移动不破坏索引中的 list 迭代器。
默认复制也有风险:新 list 有自己的节点,复制 map 却只复制了指向旧 list 的迭代器值。正确复制需要遍历新链表重建索引。本例删除了复制构造、复制赋值、移动构造与移动赋值。某些分配器条件下可以设计正确移动,但仍需处理两个成员的关联、失败路径和源对象状态,不能从单个容器可移动直接推出组合类的契约。
FaultAllocator 只为测试加入,它把实际分配转交给 std::allocator,并在指定的分配调用抛出 bad_alloc。list 和 map 的 allocator rebind 共享同一测试计数,释放不抛出;相关接口要求见 allocator.requirements。全局探针仅用于有界单线程测试,不是生产内存池。
C++ runnable demo
核心缓存后面附有线性 vector 参考模型、边界断言和故障注入。阅读时先检查 get、put、erase,再看 CacheTestAccess::check 如何验证索引与节点对应关系。参考模型不保存 list 迭代器,用独立表示降低两份实现复制同一错误的概率。
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <list>
#include <memory>
#include <new>
#include <optional>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
// Single-threaded test instrumentation, shared by allocator rebinds.
struct AllocationProbe {
static inline std::optional<std::size_t> remaining;
static inline std::size_t calls = 0;
static inline std::size_t live_blocks = 0;
};
template <class T>
struct FaultAllocator {
using value_type = T;
using is_always_equal = std::true_type;
FaultAllocator() noexcept = default;
template <class U>
FaultAllocator(const FaultAllocator<U>&) noexcept {}
[[nodiscard]] T* allocate(std::size_t count) {
++AllocationProbe::calls;
if (AllocationProbe::remaining) {
if (*AllocationProbe::remaining == 0) throw std::bad_alloc{};
--*AllocationProbe::remaining;
}
T* result = std::allocator<T>{}.allocate(count);
++AllocationProbe::live_blocks;
return result;
}
void deallocate(T* pointer, std::size_t count) noexcept {
assert(AllocationProbe::live_blocks > 0);
--AllocationProbe::live_blocks;
std::allocator<T>{}.deallocate(pointer, count);
}
template <class U>
bool operator==(const FaultAllocator<U>&) const noexcept { return true; }
};
struct IntHash {
std::size_t operator()(int key) const noexcept { return std::hash<int>{}(key); }
};
struct IntEqual {
bool operator()(int left, int right) const noexcept { return left == right; }
};
using Entry = std::pair<int, int>;
struct CacheTestAccess;
class LruCache {
using Order = std::list<Entry, FaultAllocator<Entry>>;
using Position = Order::iterator;
using IndexEntry = std::pair<const int, Position>;
using Index = std::unordered_map<int, Position, IntHash, IntEqual,
FaultAllocator<IndexEntry>>;
std::size_t capacity_;
Order order_; // MRU at front; LRU at back.
Index index_; // Destroy index before the list to which its iterators refer.
friend struct CacheTestAccess;
public:
explicit LruCache(std::size_t capacity) : capacity_(capacity) {}
LruCache(const LruCache&) = delete;
LruCache& operator=(const LruCache&) = delete;
LruCache(LruCache&&) = delete;
LruCache& operator=(LruCache&&) = delete;
[[nodiscard]] std::size_t size() const noexcept { return order_.size(); }
[[nodiscard]] std::optional<int> get(int key) {
const auto found = index_.find(key);
if (found == index_.end()) return std::nullopt;
const auto node = found->second;
order_.splice(order_.begin(), order_, node);
return node->second; // An owning int copy, not a borrowed reference.
}
void put(int key, int value) {
if (capacity_ == 0) return;
if (const auto found = index_.find(key); found != index_.end()) {
found->second->second = value;
order_.splice(order_.begin(), order_, found->second);
return;
}
order_.emplace_front(key, value);
try {
const bool inserted = index_.emplace(key, order_.begin()).second;
assert(inserted); // Fixed equality, no concurrency, and a preceding miss.
} catch (...) {
order_.pop_front();
throw;
}
// Fixed int hash/equality/destruction and deallocation do not throw.
// No map iterator obtained before emplace is used after a possible rehash.
if (order_.size() > capacity_) {
const auto erased = index_.erase(order_.back().first);
assert(erased == 1);
order_.pop_back();
}
}
bool erase(int key) {
const auto found = index_.find(key);
if (found == index_.end()) return false;
const auto node = found->second;
index_.erase(found);
order_.erase(node);
return true;
}
[[nodiscard]] std::vector<Entry> snapshot() const {
return {order_.begin(), order_.end()};
}
};
struct CacheTestAccess {
static void check(const LruCache& cache) {
assert(cache.order_.size() == cache.index_.size());
assert(cache.size() <= cache.capacity_);
for (auto node = cache.order_.begin(); node != cache.order_.end(); ++node) {
const auto found = cache.index_.find(node->first);
assert(found != cache.index_.end());
assert(found->second == node);
}
}
static void rehash(LruCache& cache, std::size_t buckets) {
cache.index_.rehash(buckets);
}
};
// Independent, deliberately linear reference model: no linked nodes or stored iterators.
class Oracle {
std::size_t capacity_;
std::vector<Entry> entries_;
public:
explicit Oracle(std::size_t capacity) : capacity_(capacity) {}
std::optional<int> get(int key) {
const auto found = std::find_if(entries_.begin(), entries_.end(),
[key](const Entry& entry) { return entry.first == key; });
if (found == entries_.end()) return std::nullopt;
const Entry entry = *found;
entries_.erase(found);
entries_.insert(entries_.begin(), entry);
return entry.second;
}
void put(int key, int value) {
if (capacity_ == 0) return;
erase(key);
entries_.insert(entries_.begin(), Entry{key, value});
if (entries_.size() > capacity_) entries_.pop_back();
}
bool erase(int key) {
const auto old_size = entries_.size();
std::erase_if(entries_, [key](const Entry& entry) { return entry.first == key; });
return old_size != entries_.size();
}
const std::vector<Entry>& snapshot() const noexcept { return entries_; }
};
void test_boundaries() {
LruCache disabled(0);
disabled.put(1, 10);
assert(disabled.size() == 0 && !disabled.get(1) && !disabled.erase(1));
LruCache single(1);
single.put(1, 10);
single.put(1, 11);
assert(single.size() == 1 && single.get(1) == 11);
single.put(2, 20);
assert(!single.get(1) && single.get(2) == 20);
assert(single.erase(2) && !single.erase(2));
LruCache cache(2);
cache.put(1, 10);
cache.put(2, 20);
const auto saved_value = cache.get(1);
cache.put(3, 30);
assert(!cache.get(2));
cache.put(3, 31);
cache.put(4, 40);
assert(!cache.get(1) && saved_value == 10);
assert((cache.snapshot() == std::vector<Entry>{{4, 40}, {3, 31}}));
CacheTestAccess::check(disabled);
CacheTestAccess::check(single);
CacheTestAccess::check(cache);
}
void test_against_oracle() {
for (std::size_t capacity = 0; capacity <= 4; ++capacity) {
LruCache cache(capacity);
Oracle oracle(capacity);
std::uint32_t state = 0x12345678U;
for (std::size_t step = 0; step < 2000; ++step) {
state = state * 1664525U + 1013904223U; // Defined unsigned wraparound.
const int key = static_cast<int>((state >> 8U) % 7U) - 3;
const int value = static_cast<int>((state >> 16U) % 1000U);
switch (state % 4U) {
case 0:
case 1:
cache.put(key, value);
oracle.put(key, value);
break;
case 2:
assert(cache.get(key) == oracle.get(key));
break;
default:
assert(cache.erase(key) == oracle.erase(key));
break;
}
if (step % 31 == 0) {
CacheTestAccess::rehash(cache, 1 + step % 257);
}
CacheTestAccess::check(cache);
assert(cache.snapshot() == oracle.snapshot());
}
}
}
void seed_cache(LruCache& cache, bool full) {
if (full) {
cache.put(1, 10);
cache.put(2, 20);
}
}
void test_allocation_failures() {
for (bool full : {false, true}) {
std::size_t allocation_count = 0;
{
LruCache cache(2);
seed_cache(cache, full);
const auto before = AllocationProbe::calls;
cache.put(3, 30);
allocation_count = AllocationProbe::calls - before;
}
assert(allocation_count > 0);
for (std::size_t fail_at = 0; fail_at < allocation_count; ++fail_at) {
LruCache cache(2);
seed_cache(cache, full);
const auto before = cache.snapshot();
const auto blocks_before = AllocationProbe::live_blocks;
AllocationProbe::remaining = fail_at;
bool caught = false;
try {
cache.put(3, 30);
} catch (const std::bad_alloc&) {
caught = true;
}
AllocationProbe::remaining.reset();
assert(caught);
assert(cache.snapshot() == before);
assert(AllocationProbe::live_blocks == blocks_before);
CacheTestAccess::check(cache);
cache.put(3, 30); // The failed operation did not make the cache unusable.
assert(cache.get(3) == 30);
}
}
}
int main() {
static_assert(!std::is_copy_constructible_v<LruCache>);
static_assert(!std::is_move_constructible_v<LruCache>);
test_boundaries();
test_against_oracle();
test_allocation_failures();
assert(AllocationProbe::live_blocks == 0);
std::cout << "LRU boundaries, 10000 oracle steps, rehash and allocation rollback: OK\n";
}
g++ -std=c++20 -O2 -Wall -Wextra -Wpedantic -Werror examples/lru-cache.cpp -o /tmp/lru-demo
/tmp/lru-demo
程序使用 C++20 标准库,平台可移植;断言必须保持启用,不要定义 NDEBUG。预期输出:
LRU boundaries, 10000 oracle steps, rehash and allocation rollback: OK
边界测试覆盖容量 0/1、命中更新、淘汰、重复删除、未命中,以及返回值在条目淘汰后仍然有效。模型测试对容量 0 至 4 各运行 2000 步,使用固定种子的有界整数轨迹,每步比较返回值和完整 MRU 到 LRU 序列。每隔 31 步请求一次不同桶数的 rehash,再检查双容器不变量;不假定实现选择某个精确桶数。
分配失败测试先测出一次新增实际经过多少次测试分配,然后每次重建同样的初态,依次令第 0、1 等次分配失败。空缓存和满缓存分别测试,失败后核对旧快照、未释放分配块数和结构一致性,再确认缓存仍可使用。计数随标准库分配策略变化,程序没有写死“新增必定分配三次”。
可另用 -D_GLIBCXX_DEBUG 在 libstdc++ 上检查迭代器误用,或启用 ASan/UBSan 检查有限执行中的内存问题。这些运行不证明所有访问轨迹都正确,也没有验证恶意哈希、任意 T 或并发访问。
高频追问
get 为什么没有 const?
命中要改变最近使用顺序。若需求包含“只看值、不延长留存优先级”,应另设不改变顺序的 peek,并让测试区分这两种访问。简单把链表标成 mutable 可以满足语法上的 const,却不会消除共享写入。
reserve 后是否就不会抖动?
unordered_map::reserve 针对桶容量,不等于预构造全部 map 节点,更不会替 list 准备节点。新增和淘汰仍有分配、析构与释放成本。本例还先保留新旧条目再淘汰,因此计划容量时需要留出临时准备空间。若要求操作期间不分配,需采用预建存储、可复用节点和确定的耗尽行为。
为什么不能把 list 换成 vector,再保存 vector 迭代器?
vector 的插入、删除和重分配有不同失效规则,移动到头部还要搬移中间元素。可以设计基于稳定槽位编号的数组链表,但那已经是另一种表示,需要维护空闲槽、前后链接和索引版本,不能直接替换容器类型。
完整缓存读取能一直使用共享锁吗?
本实现的命中会写链表,应该用同一把独占锁保护索引和值及顺序变化,并在解锁前取得安全返回值。分片可以分散竞争,但每片维护的只是局部 LRU。近似更新顺序可以减少共享写入,代价是淘汰语义变化,需要测它对命中率与延迟的影响。
容易答错的点
- 把 LRU 解释成淘汰访问次数最少的键。本文维护最近访问顺序,没有频次计数。
- 每次
put都先淘汰。已有键更新不增加条目;新键也要准备成功后才淘汰,才能保留失败时的旧状态。 - 认为 rehash 会让索引中保存的 list 迭代器失效。rehash 操作的是哈希容器;list 节点生命周期由链表操作决定。
- 用哈希表
operator[]查找缺失键。它可能插入默认值,本实现应使用find,不能留下未关联有效节点的索引项。 - 直接复制含有跨成员迭代器的类。逐成员复制不会自动把旧链表迭代器映射到新节点。
- 把
get的借用引用直接返回给解锁后的调用者。另一个线程可能立即淘汰对应节点;返回值副本或具有明确所有权的对象才便于约定生命周期。 - 把节点数上限称为严格内存上限。桶数组、节点头、分配器开销和准备阶段的新节点都需要计算。
性能分析
令 n 为当前条目数,B 为哈希桶数;固定整数键使哈希和比较本身为常数工作。
| 操作 | 平均复杂度 | 最坏复杂度 | 额外工作 |
|---|---|---|---|
get | O(1) | O(n) | 命中后常数时间 splice |
put | O(1) | O(n) | 新节点分配、可能扩容、满时淘汰 |
erase | O(1) | O(n) | 哈希查找与删除,加链表单节点删除 |
snapshot | O(n) | O(n) | 分配并复制全部条目 |
显式 rehash | O(n) | O(n²) | 重建桶组织,测试专用访问器调用 |
复杂度按 无序容器操作要求 与 list 的单节点操作组合,不能只报链表移动的 O(1)。标准给出的平均复杂度也不代表某次操作的时间上界。测试检查器会遍历并查找全部条目,它的成本不属于核心 get/put,基准测试时不应把每步检查算进缓存 API 耗时。
空间应写成 O(n + B),包括节点和桶。桶数会受 reserve/rehash 及实现策略影响,不能只用当前条目数推算实际内存。缓存满时,每个新键都经历新节点分配与旧节点释放,可能改变分配器状态和尾延迟;预留桶并不能消除这些动作。
评估策略时回放保留时间顺序的轨迹,覆盖冷启动、稳定热点和一次性扫描。只用均匀随机访问会掩盖时间局部性。分别记录命中率、淘汰率、每次分配、缓存操作 p50/p99/p99.9,以及未命中回源后的端到端延迟。若增加锁或分片,还需测锁等待和热点片负载。本文没有性能实测,不给出固定吞吐或加速倍数。
Quant/Low-Latency 场景
可重建的证券元信息、格式化结果或历史查询结果可以作为缓存候选,但键要包含影响结果的版本或上下文。风控配置和证券状态变化时,需要失效通知或版本校验;“LRU 命中”只说明条目仍驻留,不能证明它对当前请求有效。
未完成订单的唯一状态、尚未确认发送结果的记录,不能因最近没有访问就被淘汰。缓存层只应保存有可靠来源的副本;发生未命中后是否能重建、重建期间是否允许继续处理,要在组件协议中说明。
市场数据回放可能突然扫描大量只用一次的键,将小工作集中的热点挤出。可以评估准入规则、分段策略或近似淘汰,但应将命中率、额外元数据和热路径写入放在同一条回放上比较。对极短处理链,list 指针访问、哈希节点与分配器开销可能已经超过省下的工作,需要先测缓存整体是否有收益。
相关专题
- RAII 与异常安全:本章插入失败回滚与延后淘汰的前置知识。
- vector 失效边界:比较两种容器保存迭代器时的约束,也用于理解线性参考模型。
- shared_mutex:检查命中路径的共享写入,以及解锁后结果的生命周期。
- CPU cache / false sharing:继续分析节点布局、共享元数据和跨核写入成本。
分层面试题
L1 先说明访问语义和容量边界,L2 沿每次操作检查两个容器何时一致,L3 再加入异常、并发和真实负载约束。作答时至少手推一条包含命中提升与满容量插入的轨迹,并指出新节点分配失败时旧尾应保留在哪里。