You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ Web缓存场景:如何在类B内创建持久化的类A实例

解决方案

方法1:使用std::shared_ptr作为类B的成员变量

这是最贴合你需求的实现方式,既能避免直接调用new,又能让A的实例在B的生命周期内持续存在,且可以在setValue()中完成初始化。

第一步:修改类B的定义

需要先包含智能指针的头文件,然后在B的私有成员中声明std::shared_ptr:

#include <memory>
#include <string>

class B{
 private:
  std::string value;
  std::string text;
  // 声明智能指针成员,默认处于空状态
  std::shared_ptr<A<std::string, std::string>> cache_ptr;
 public:
  void setValue();
  std::string getResult();
};

第二步:在setValue()中初始化智能指针

用std::make_shared创建A的实例,这是C++推荐的智能指针初始化方式,无需手动调用new:

void B::setValue() {
    int capacity = 100; // 这里替换成你实际确定容量的逻辑
    // 创建A的实例并绑定到智能指针
    cache_ptr = std::make_shared<A<std::string, std::string>>(capacity);
    
    // 直接调用put方法操作缓存
    cache_ptr->put("user_id", "12345");
}

第三步:在B的其他函数中使用缓存

比如在getResult()里,可以直接通过智能指针访问A的实例,记得先判断指针是否有效:

std::string B::getResult() {
    if (cache_ptr) {
        // 这里结合缓存逻辑处理业务,比如从缓存取值后拼接结果
        return "缓存处理完成:" + value;
    }
    return "缓存未初始化";
}

方法2:直接将A作为类B的成员(适用于容量提前确定的场景)

如果capacity的值在创建B对象时就能确定,不需要等到setValue()才获取,那可以直接把A作为B的成员变量,完全不需要指针:

class B{
 private:
  std::string value;
  std::string text;
  A<std::string, std::string> cache;
 public:
  // 在构造函数中初始化缓存容量
  B(int cap) : cache(cap) {}
  
  void setValue() {
      cache.put("key", "value"); // 直接调用put方法
  }
  std::string getResult();
};

你之前的方法问题出在哪?

  • 引用成员:C++的引用必须在对象构造时就绑定到有效对象,无法在后续的setValue()中再赋值绑定新实例;如果绑定局部对象,还会出现悬空引用(局部对象销毁后引用失效)。
  • 局部对象:setValue()里的_a是栈上局部对象,函数执行完毕就会被销毁,自然无法在B的其他函数中复用。

内容的提问来源于stack exchange,提问作者Keorus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:25:30