管理 unique_ptr 向量的正确方法是什么?

What is the proper way to manage a vector of unique_ptr's?

如果我有一个 class 正在管理一个 std::unique_ptr 向量,管理该资源的正确方法是什么?我有一个最低限度的工作示例。但是,当 运行 此代码时,会发生分段错误。我想这是因为 mains 对 bin 的引用在 AContainer::addValue 中得到了 std::moved,但我不确定,我不确定如何测试该假设.

#include <memory>
#include <vector>
#include <iostream>

class AnotherContainer;

class AContainer{
    public:
        void addValue(AnotherContainer& anInt);
        const std::vector<std::unique_ptr<AnotherContainer>>& getVals() const;
    private:
        std::vector<std::unique_ptr<AnotherContainer>> ints;
};

void AContainer::addValue(AnotherContainer& anInt){
    ints.push_back(std::move(std::unique_ptr<AnotherContainer>(&anInt)));
}

const std::vector<std::unique_ptr<AnotherContainer>>& AContainer::getVals() const{
    return ints;
}

class AnotherContainer{
    public:
        AnotherContainer(int val) : myVal(val){};
        int getVal() const{
            return myVal;
        }
    private:
        int myVal;
};

int main(){
    AContainer bin;
    AnotherContainer val1(1), val2(2);
    bin.addValue(val1);
    bin.addValue(val2);
    const std::vector<std::unique_ptr<AnotherContainer>>& vals = bin.getVals();
    std::cout << "vals[0] = " << vals[0]->getVal() << std::endl;
    return 0;
}

发生的事情是您在此处的堆栈上创建了两个 AContainer 实例:

AnotherContainer val1(1), val2(2);

然后在 addValue 调用中包装指向这些引用的指针:

bin.addValue(val1);
bin.addValue(val2);

所以,当调用main函数时returns,栈上创建的对象val1和val2被删除了,而且在删除bin时也被删除了,因为智能指针调用了析构函数它们包裹的对象,从而导致分段错误。

智能指针用于管理堆上的内存,使用 new 运算符分配,因此为了 运行 顺利进行,您应该以这种方式初始化 val1 和 val2 :

AnotherContainer* val1 = new AnotherContainer(1);
AnotherContainer* val2 = new AnotherContainer(2);

(您还必须对方法进行一些更改才能编译程序)