2014-02-13 42 views
5

我只是想確定一下。用C++替換malloc/free /刪除

這是我的代碼

int * Image = (int *)malloc(sizeof(int) * m_Width/2 * m_Height); 
free(Image); 

,如果我想使用新的代替malloc和free,而不是刪除。 這就是我寫的

int* Image = new int[m_Width/2 * m_Height]; 
delete[] Image; 

這是正確的嗎?

+3

這的確是正確的。我不認爲這是值得回答的。 –

+0

只是確保我將刪除問題 – Gilad

+0

不要刪除它,這是任何其他人都有同樣問題的好例子。 – IllusiveBrian

回答

3

從技術上講,這是正確的。然而,這是C++我們談論和C++的方式動態地分配的陣列是使用std:vector代替:

std::vector<int> Image(m_Width/2 * m_Height); 

或者:

std::vector<int> Image; 
Image.resize(m_Width/2 * m_Height); 

存儲器將自動當釋放當它超出範圍時,std::vector被破壞。

+0

你指的是沒有指針的矢量嗎? – MahanGM

+0

原始代碼正在分配一個「int」值的數組,因此您將創建一個「int」值的「std :: vector」。 –

+0

是的,我只是想說清楚,如果像OP這樣的人正在看答案。 – MahanGM

2

這是正確的。但是如果你想獲得一些額外的語義而沒有太多的OOP開銷,你可以使用unique_ptr:

unique_ptr<int[]> Image(new int[m_Width/2 * m_Height]); 
// do something with Image... 
Image.Reset(); // call it if you want to free memory manually, 
       // or just leave until Image is destroyed.