mardi 26 février 2019

Acceptable practice with creating objects that are mutually dependent on it's "container" class?

Say I have a class structure that could hold a group of objects, and that the objects that it was containing needed to have access to the container that itself is contained in. Here is an example class structure of what I am talking about:

class Item;
class Container {
private:
    std::vector<Item*> items;
    ....
public:
    void add(Item *newItem) {
        items.push_back(newItem);
    }
    ....
}

class Item {
private:
    int data;
    Container* container;
    ....
public:
    Item(int data, Container* container) {
        this->data = data;
        this->container = container;
        if(container != nullptr) {
            container.add(this);
        }
    }
    ....
}

This would allow me to create an object easily like this:

Container contain;
new Item(1, &contain);
new Item(2, &contain);
new Item(3, &contain);

I could then easily access these objects through the container object, and this would by no means cause a memory leak by freely creating objects like this.

However, is this bad practice to create objects this way? Also, instead of accessing the container directly through a pointer stored in the objects themselves, should I just pass the container as a function parameter for whenever it needs to be used?

Aucun commentaire:

Enregistrer un commentaire