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

C++方法链调用时修改类实例成员不生效问题排查

问题原因

你的SectionManager::getSection方法返回的是Section类型的值拷贝,而非原对象的引用。每次调用manager.getSection(0)都会生成一个存储在栈上的临时Section对象,你调用addRange修改的是这个临时拷贝,调用结束后临时对象立即销毁,存储在SectionManager内部的原Section对象没有发生任何修改,所以最终查询计数永远为0。
你尝试取临时对象地址报错也是这个原因:C++标准禁止对生命周期即将结束的右值临时对象取地址,避免出现野指针问题。

修复方案

将getSection方法的返回值修改为Section的左值引用即可,修改后的代码如下:

class SectionManager {
  public:
    SectionManager(){}
    
    void addSections(int total) {
       for(int i = 0; i < total; i++) {
           _sections[i] = Section();
       }
       _totalSections += total;
    }
    
    // 返回引用,直接指向内部存储的原对象
    Section& getSection(int index){
        return _sections[index];
    }
    // 可选:添加const版本供只读场景使用
    const Section& getSection(int index) const {
        return _sections[index];
    }
    
    int getTotalSections(){
        return _totalSections;
    }
  
  private:
    int _totalSections = 0;
    Section _sections[TOTAL_SECTIONS];
  
};

修改后调用manager.getSection(0).addRange会直接修改SectionManager内部存储的Section对象,你的测试代码运行后会输出正确的Range计数。

补充建议

如果你的项目支持C++标准库,也可以用std::vector替代固定长度的数组存储Range和Section实例,避免硬编码TOTAL_RANGES、TOTAL_SECTIONS这类宏限制容量,同时自动处理内存管理,降低出错概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:48:03