简体   繁体   中英

C++: How to properly delete array of pointers to pointers in class destructor

I am having trouble understanding how to write the destructor in the second class of the program below:

class First
{
    // Assume this is a virtual class
};

class Second
{
    private:
        int index;
        First **arr;

    public:
        Second(int size)
        {
            index = 0;
            arr = new First*[size]; // Please bear with my use of new
        }

        ~Second() {}

        void add(First *f)
        {
            arr[index++] = f;
        }
};

In all of the similar questions I found, each element of the array is assigned a value dynamically, using new as such: arr[i] = new First(); . However, here the elements are assigned the value of a pointer to an object that is a parameter of the function. So, should the destructor delete every element one by one and then delete the array, or is ti enough to delete the array?

~Second()
{
    for(int i = 0; i < index; ++i) delete[] arr[i]; // Is this necessary?
    delete[] arr;
}

You'd better keep NULLs in the array after allocation in the constructor first.

    int arr_size; // you need to define this for the reference in destructor

    Second(int size)
    {
        arr_size = size;
        arr = new First*[size]; // Please bear with my use of new
        for (int i = 0; i < size; i++)
            arr[i] = NULL;
    }

Then, in the destructor, delete the element only if it's not NULL as below.

    ~Second()
    {
        for(int i = 0; i < arr_size; i++)
            if (arr[i]) 
                delete arr[i];
        delete[] arr;
    }

In all of the similar questions I found, each element of the array is assigned a value dynamically, using new as such: arr[i] = new First(); . However, here the elements are assigned the value of a pointer to an object that is a parameter of the function. So, should the destructor delete every element one by one and then delete the array, or is it enough to delete the array?

That, we cannot answer. Does Second take ownership of the objects passed to .add() , and if so how were they allocated?

  1. If it does not take ownership, just deleting the array is enough, and that array should be managed by a std::unique_ptr doing so for you.

  2. If it does take ownership, that argument to .add() should be the smart-pointer with the right ownership-semantics and deleter. Your array should then be an array of those smart-pointers, managed by a std::unique_ptr .

In either case, if you properly use smart-pointers, the default-dtor is fine.

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