dimanche 29 mars 2020

How to delete a pointer belonging to an object stored in a vector?

I have a Containing class, a Contained class, and a Data class. That Containing class holds a vector of Contained objects. The Contained class holds a pointer to a data object, allocated on the heap in Contained's constructor. However, I can't deallocate it in the destructor, since the vector will create copies of Contained and then destroy them, thus destroying the data pointer even in the copy we're using.

TL;DR Here's some code to explain:

class Data {
    public:
        Data();
};

class Contained {
    private:
        Data* data;
    public:
        Contained();
        // what should I add ? a copy constructor ? an assignement operator ? and how
};

class Container {
    private:
        vector<Contained> rooms;
    public:
        //some member functions
};
Contained::Contained() {
    data = new Data();
}

Where do I delete data ?

Aucun commentaire:

Enregistrer un commentaire