[英]C++: How to properly delete array of pointers to pointers in class destructor
我在理解如何在以下程序的第二類中編寫析構函數時遇到了麻煩:
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;
}
在我發現的所有類似問題中,使用new這樣的方法為數組的每個元素動態分配一個值:
arr[i] = new First();
。 但是,此處為元素分配了指向對象的指針的值,該對象是函數的參數。 那么,析構函數應該先刪除每個元素然后刪除數組,還是足以刪除數組?
那,我們不能回答。 Second
是否對傳遞給.add()
的對象擁有所有權,如果是,則如何分配它們?
如果沒有所有權,只需刪除該數組就足夠了,該數組應該由std::unique_ptr
來管理。
如果確實擁有所有權,則.add()
參數應該是具有正確的所有權語義和刪除器的智能指針。 然后,您的數組應該是由std::unique_ptr
管理的那些智能指針的數組。
無論哪種情況,如果您正確使用智能指針,則default-dtor都可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.