C++:如何在 class 析构函数中正确删除指向指针的指针数组

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

我无法理解如何在下面程序的第二个 class 中编写析构函数:

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

在我发现的所有类似问题中,数组的每个元素都被动态分配一个值,使用 new 这样的: arr[i] = new First(); 。然而,这里的元素被分配了指向对象的指针的值,该对象是函数的参数。那么,析构函数应该一个一个地删除每个元素然后删除数组,还是只删除数组?

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

你最好先在构造函数中分配后在数组中保留 NULL。

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

然后,在析构函数中,仅当元素不为 NULL 时才将其删除,如下所示。

    ~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?

那个,我们无法回答。 Second 是否拥有传递给 .add() 的对象的所有权?如果是,它们是如何分配的?

  1. 如果它没有取得所有权,只需删除数组就足够了,该数组应该由 std::unique_ptr 为您管理。

  2. 如果它确实获得了所有权,那么 .add() 的参数应该是 smart-pointer 和正确的 ownership-semantics 和删除器。然后,您的数组应该是那些 smart-pointer 的数组,由 std::unique_ptr.

  3. 管理

无论哪种情况,如果您正确使用 smart-pointers,default-dtor 都可以。