MST

星途 面试题库

面试题:C++中std::weak_ptr在复杂场景下的应用

假设你正在开发一个缓存系统,使用std::shared_ptr来管理缓存对象。为了避免缓存对象被过度引用而不能及时释放,同时又要能随时检查缓存对象是否还存在,你将如何运用std::weak_ptr实现这个功能?请详细描述设计思路并给出关键代码片段。
38.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 使用std::shared_ptr来实际管理缓存对象,以提供共享所有权语义。
  2. 同时,在需要检查对象是否存在但不增加引用计数的地方,使用std::weak_ptr
  3. 当向缓存中插入对象时,创建std::shared_ptr并存储,同时创建对应的std::weak_ptr作为备份。
  4. 当检查缓存对象是否存在时,通过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;
}