简体   繁体   中英

C++ - how to delete sub-classes in destructor

Here is a class definition:

class Person {
private:
    char* name;
    int numChildren;
    Person** childrenList;
public:
    Person(char* name);
    ~Person();
};

In the Person::Person() constructor, it will set up the name of the person based on the constructor parameter, and then create Person object for each child, and each child may have other children. And let's say for one case, after I run this: Person* me = new Person("Alex"); , the following structure will be created: 在此处输入图片说明 ie if me is created, me 's children will also be recursively created.

But I have a trouble in the Person::~Person() destructor. In the destructor it should delete all dynamic objects including name and every child. Here is my attempt:

Person::~Person() {
    for (int i = 0; i < numChildren; i++) {
        // go inside each child
    }
    delete[] this->name;
    delete[] childrenList;
}

But I don't know how to go inside each child, and the destructor has no parameter.

Could anyone give me some hint? Thanks!

Just delete each child before you delete[] childrenlist :

Person::~Person()
{
    for (int i = 0; i < numChildren; i++) {
        delete childrenList[i];
    }
    delete[] childrenList;
    ...
}

when using a double poiner like Person** childrenList , you have to do this to allocate and delete it:

    unsigned len1 = 100;
    unsigned len2 = 100;

    //  childrenList is a pointer to a an array of pointers
    Person** childrenList = nullptr;

    // create an array with UNALLOCATED Person pointers, note the "*"
    childrenList = new  Person*[len1];          

    // allocate all the pointers in the the array
    for (size_t i1 = 0; i1 < len1; i1++)
        childrenList[i1] = new Person;


    // delete all the pointer in the array
    for (size_t i1 = 0; i1 < len1; i1++)
        if (childrenList[i1])
            delete childrenList[i1];        

    // delete the array itself
    delete[] childrenList;

you could put this in your destructor:

Person::~Person()
{
// delete all the pointer in the array
        for (size_t i1 = 0; i1 < len1; i1++)
            if (childrenList[i1])
                delete childrenList[i1];        

        // delete the list itself
        delete[] childrenList;

}

But this whole thing would be done easier with a "2d" std::vector:

vec<vec<Person>> childrenList;

Such a 2d vector has its own syntax, but it is easier and less error prone than "bare" pointers/arrays.- PS: I have NOT tried to compile or run this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM