lundi 31 juillet 2017

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

If I have a class which is managing a vector of std::unique_ptrs, what is the proper way to manage this resource? I have below a minimum working example. When running this code, however, a segmentation fault occurs. I imagine this is because mains reference to bin get's std::moved in AContainer::addValue, but I don't know for sure and I am not sure how to test that assumption.

#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;
}

Aucun commentaire:

Enregistrer un commentaire