2013-08-05 117 views
1

我正在使用GNU編譯器。類B中的虛擬析構函數不調用Destructor〜D()。有誰能告訴我爲什麼?虛擬析構函數:不工作?

#include<iostream> 
using namespace std; 

class B { 
    double* pd; 
    public: 
    B() { 
    pd=new double [20]; 
    cout<< "20 doubles allocated\n"; 
    } 

    virtual ~B() { //the virtual destructor is not calling ~D() 
    delete[] pd; 
    cout<<"20 doubles deleted\n"; 
    } 

    }; 

class D: public B { 
    int* pi; 
    public: 
    D():B() { 
    pi= new int [1000]; 
    cout<< "1000 ints allocated\n"; 
    } 
    ~D() { 
    delete[] pi; 
    cout< "1000 ints deleted\n"; 
    } 
    }; 

int main() { 
    B* p= new D; //new constructs a D object 

刪除應調用類B中的虛擬析構函數,但它不。

delete p; 
    } 
+1

'cout <「1000 ints deleted \ n」;'你在那裏得到一個錯字 – Borgleader

+0

這應該工作(如果它編譯,你有一個微不足道的語法錯誤)。你有什麼證據證明它沒有? – juanchopanza

+0

謝謝你們。 –

回答

8

確實如此,你只是沒有看到輸出,因爲你有一個錯字:

cout < "1000 ints deleted\n"; 
// ^, less than 

你的編譯器過於寬鬆,這不應該編譯(至少用C++ 11)。

這可能確實是因爲basic_ios::operator void*使一個流對象隱式轉換爲void*和你的編譯器被允許到char*一個字串衰減(這是轉換爲void*)。 cout < "x";然後只是使用內置的operator<(void*, void*)做指針比較並丟棄結果。