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

C++中无需手动内存管理解决Storage对象引用失效问题

解决悬垂引用问题:用智能指针替代std::reference_wrapper

你遇到的核心问题是悬垂引用:temp()函数中的局部对象t4在函数返回后被销毁,但Storage里的std::reference_wrapper还指向这个已失效的内存,后续访问会触发未定义行为(也就是你看到的"Not found!!"或者更严重的崩溃)。同时你需要保持对象修改的同步性,不能回到std::list<Thing>的拷贝方案。

最适合的解决方案是改用智能指针——具体来说是std::shared_ptr,它既能帮你自动管理对象生命周期,又能保证多个指向同一对象的指针共享实例,修改同步。

修改后的代码实现

首先调整Storage类,将存储容器改为std::list<std::shared_ptr<Thing>>,同时更新add和findById方法:

#include <iostream>
#include <list>
#include <memory> // 引入shared_ptr头文件
class Thing {
private:
    int id;
    int value = 0;
    static int nextId;
public:
    Thing() { this->id = Thing::nextId++; };
    int getId() const { return this->id; };
    int getValue() const { return this->value; };
    void add(int n) { this->value += n; };
};
int Thing::nextId = 1;
class Storage {
private:
    std::list<std::shared_ptr<Thing>> list;
public:
    void add(std::shared_ptr<Thing> thing) { 
        this->list.push_back(thing); 
    }
    std::shared_ptr<Thing> findById(int id) const {
        // 用范围for循环简化迭代逻辑
        for (const auto& ptr : this->list) {
            if (ptr->getId() == id) {
                return ptr;
            }
        }
        std::cout << "Not found!!\n";
        exit(1);
    }
};

然后更新业务代码,用std::make_shared创建Thing实例,确保所有对象都由智能指针管理:

void temp(Storage& storage) {
    storage.findById(2)->add(1);
    // 用make_shared创建t4,智能指针会自动管理其生命周期
    auto t4 = std::make_shared<Thing>();
    t4->add(50);
    storage.add(t4);
    std::cout << storage.findById(4)->getValue() << "\n";
}
void run() {
    auto t1 = std::make_shared<Thing>();
    t1->add(10);
    auto t2 = std::make_shared<Thing>();
    t2->add(100);
    auto t3 = std::make_shared<Thing>();
    t3->add(1000);
    Storage storage;
    storage.add(t3);
    storage.add(t1);
    storage.add(t2);
    temp(storage);
    t2->add(10000);
    std::cout << storage.findById(2)->getValue() << "\n";
    std::cout << storage.findById(4)->getValue() << "\n";
}

为什么这个方案可行?

  1. 自动内存管理:std::shared_ptr采用引用计数机制,只要有至少一个shared_ptr指向Thing对象,对象就会保持存活。temp()中的t4被添加到Storage后,Storage的list里的shared_ptr会持有对象的引用,所以函数返回后t4不会被销毁。
  2. 修改同步:所有指向同一Thing的shared_ptr都引用同一个实例,外部修改(比如run()中t2->add(10000))会直接反映到Storage中的对象上,完美保留了你需要的同步特性。
  3. 避免悬垂引用:不再依赖裸引用或reference_wrapper,智能指针从根本上消除了悬垂引用的风险,因为对象的生命周期由指针的引用计数决定。

其他可选方案(不推荐)

如果你不想用shared_ptr,也可以让Storage完全拥有对象的所有权(比如用std::list<std::unique_ptr<Thing>>),但这样外部无法持有对象的引用,也就无法实现外部修改同步到Storage的需求,所以shared_ptr是最贴合你场景的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:08:50