簡體   English   中英

C++ 中的 delete 與 delete[] 運算符

[英]delete vs delete[] operators in C++

C++ 中的deletedelete[]運算符有什么區別?

delete運算符釋放內存並為使用new創建的單個對象調用析構函數。

delete []運算符釋放內存並為使用new []創建的對象數組調用析構函數。

new []返回的指針使用delete或對new返回的指針使用 delete delete []會導致未定義的行為。

delete[]<\/code>運算符用於刪除數組。 delete<\/code>運算符用於刪除非數組對象。 它分別調用operator delete[]<\/code>和operator delete<\/code>函數來刪除數組或非數組對象在(最終)調用數組元素或非數組對象的析構函數后占用的內存。

以下顯示了關系:

typedef int array_type[1];

// create and destroy a int[1]
array_type *a = new array_type;
delete [] a;

// create and destroy an int
int *b = new int;
delete b;

// create and destroy an int[1]
int *c = new int[1];
delete[] c;

// create and destroy an int[1][2]
int (*d)[2] = new int[1][2];
delete [] d;

這是 c++ malloc<\/code> \/ free<\/code> , new<\/code> \/ delete<\/code> , new[]<\/code> \/ delete[]<\/code>中 allocate\/DE-allocate 模式的基本用法

我們需要相應地使用它們。 但我想對delete<\/code>和delete[]<\/code>之間的區別添加這種特殊的理解

1) delete<\/code>用於解除分配給單個對象<\/strong>的內存

2) delete[]<\/code>用於取消分配為對象數組<\/strong>分配的內存

class ABC{}

ABC *ptr = new ABC[100]

運算符deletedelete []分別用於銷毀使用newnew[]創建的對象,返回到編譯器內存管理器可用的已分配內存。

new創建的對象必須用delete銷毀,用new[]創建的數組應該用delete[]

當我問這個問題時,我真正的問題是,“兩者之間有區別嗎?運行時不是必須保留有關數組大小的信息,所以它不能分辨出我們指的是哪一個嗎?” 這個問題沒有出現在“相關問題”中,所以只是為了幫助像我這樣的人,這里是答案: “為什么我們甚至需要 delete[] 運算符?”<\/a>

"

C++ delete[] 運算符確保調用所有分配給 new[] 的 object 的析構函數。 以下示例演示了相同的內容。 此外,當 class 具有非默認析構函數以釋放獲取的資源時,必須首選 delete[](如果以前使用 new[])。 否則,可能會導致 memory 泄漏。

通用代碼:-

#include <iostream>
using namespace std;

class memTest{
    public:
    static int num;
    memTest(){
cout<<"Constructor from object " << num++ << endl;
    }
    ~memTest(){
cout<<"Destructor from object " << --num << endl;        
    }
};
int memTest::num=0;

示例 1:- 使用 new[] 和 delete 可能會導致未定義的行為。

int main() {
    memTest* Test1=new memTest[3];
    
    delete Test1; //<-----
    return 0;
} 

Output 1:-

Constructor from object 0
Constructor from object 1
Constructor from object 2
Destructor from object 2 //<-----

示例 2:正確的行為是使用 new[] 和 delete[]。

int main() {
    memTest* Test1=new memTest[3];
    
    delete[] Test1; //<-----
    return 0;
} 

Output 2:-

Constructor from object 0
Constructor from object 1
Constructor from object 2
Destructor from object 2
Destructor from object 1 //<-----
Destructor from object 0 //<-----

delete<\/code>用於單個指針, delete[]<\/code>用於通過指針刪除數組。 這<\/a>可能會幫助您更好地理解。

"

好吧..也許我認為這只是為了明確。 運算符delete和運算符delete []是區分的,但delete運算符也可以釋放數組。

test* a = new test[100];
delete a;

並且已經檢查過此代碼沒有內存泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM