2016-11-05 182 views
3

這段代碼中的析構函數和DeAllocate函數有什麼區別?析構函數和函數之間的區別是什麼?

我不明白它們對我來說看起來像是一樣的東西。它們完全一樣,爲什麼你需要像DeAllocate這樣的函數?析構函數具有自動調用的好處,但DeAllocate不會。

#include <iostream> 
using namespace std; 

const int SIZE=5; 

class ARRAY_CLASS 
{ 
public: 
    ARRAY_CLASS();//default constructor 
    ~ARRAY_CLASS(); //destructor 
    void Add(int); //mutator 
    void Print(); //accessor 
    int * Get_Address(); //accessor 
    void DeAllocate(); //mutator 
private: 

    int *A; 
    int count; 
}; 

ARRAY_CLASS::ARRAY_CLASS() 
{ 
    cout<<"Default constructor has been called\n"; 
    A = new int[SIZE]; 
    count = 0; 
} 


ARRAY_CLASS::~ARRAY_CLASS() 
{ 
    cout<<"The Destructor has been Called!\n"; 
    delete [ ] A; 
    A=0; 
    count = 0; 
} 

void ARRAY_CLASS::Add(int item) 
{ 
    if (count<SIZE) 
     A[count++]=item; 
    else 
     cout<<"Array Full\n"; 
} 
void ARRAY_CLASS::Print() 
{ 
    for(int i=0; i<count; i++) 
     cout<<"A[i] = "<<A[i]<<endl; 
} 

int * ARRAY_CLASS::Get_Address() 
{ 
    return A; 
} 

void ARRAY_CLASS::DeAllocate() 
{ 
    delete [ ] A; 
    A = 0; 
    count = 0; 
} 

int main() 
{ 

    ARRAY_CLASS B; 

    B.Add(1); 
    B.Add(2); 
    B.Add(3); 
    B.Add(4); 
    B.Add(5); 

    B.Print(); 

    ARRAY_CLASS A = B; 

    cout<<"A holds address location = "<<A.Get_Address() 
    <<" and B holds address location "<<B.Get_Address()<<endl; 

    B.DeAllocate(); 
    A.Print(); 

    return 0; 
} 
+2

*析構函數具有自動調用的好處,但DeAllocate不會。*就是這樣。認真。除此之外,再看看。 RAII依賴於此。在大多數語言中都存在相同的概念,甚至是託管的概念(例如,在C#中將'IDisposable'與'using'結合起來使用)。這使我們的日常生活變得更好。 –

+0

偏題:強烈推薦'A = nullptr;'over'A = 0;'。第一個意圖對於不經意的讀者來說更爲明顯。 – user4581301

+1

'DeAllocate()'方法在這裏可能不應該存在。它使對象處於無效狀態。應該只有一個析構函數。 – EJP

回答

4

人們可能確實改寫了析構函數:

ARRAY_CLASS::~ARRAY_CLASS() 
{ 
    cout<<"The Destructor has been Called!\n"; 
    DeAllocate(); 
} 

的不同之處在於:

  • 析構函數離開範圍時,在銷燬調用(自動爲本地對象,其中,對象被創建,或者當對象被刪除以獲得freestore對象時)。對象被銷燬後,該對象不再存在。

  • 當您調用DeAllocate();時,數組的內存被釋放並且對象的狀態發生變化,但其所有成員和ARRAY_CLASS對象本身仍然存在。

3

析構函數會在對象本身被移除時發生。

在您發佈的示例中,您可以簡單地將該函數重命名爲其他內容,如void ARRAY_CLASS::ClearArray()而不是void ARRAY_CLASS::DeAllocate()。你所做的只是釋放A使用的內存,而不是破壞整個對象。

+0

但是那麼調用兩者會有什麼意義呢? –

+0

你不要調用析構函數。當你刪除一個對象或失去範圍時會發生這種情況。 – rebnat

+1

在你發佈的例子中,如果數組是你擔心清理的唯一數據,那麼你可以讓析構函數調用deallocate函數。 – rebnat

相關問題