面试题答案
一键面试设计思路
- 使用
std::shared_ptr
来实际管理缓存对象,以提供共享所有权语义。 - 同时,在需要检查对象是否存在但不增加引用计数的地方,使用
std::weak_ptr
。 - 当向缓存中插入对象时,创建
std::shared_ptr
并存储,同时创建对应的std::weak_ptr
作为备份。 - 当检查缓存对象是否存在时,通过
std::weak_ptr
尝试锁定对象,如果能成功锁定,说明对象还存在,否则对象已被释放。
关键代码片段
#include <iostream>
#include <memory>
#include <unordered_map>
// 缓存系统类
class CacheSystem {
public:
// 向缓存中插入对象
void insert(const std::string& key, std::shared_ptr<int> value) {
cache[key] = value;
weakCache[key] = value;
}
// 检查缓存对象是否存在
bool exists(const std::string& key) {
auto it = weakCache.find(key);
if (it != weakCache.end()) {
return it->second.lock() != nullptr;
}
return false;
}
private:
std::unordered_map<std::string, std::shared_ptr<int>> cache;
std::unordered_map<std::string, std::weak_ptr<int>> weakCache;
};
你可以这样使用上述代码:
int main() {
CacheSystem cache;
auto value = std::make_shared<int>(42);
cache.insert("key1", value);
std::cout << "Exists: " << (cache.exists("key1")? "Yes" : "No") << std::endl;
// 手动释放共享指针,模拟对象被释放
value.reset();
std::cout << "Exists after release: " << (cache.exists("key1")? "Yes" : "No") << std::endl;
return 0;
}