2017-10-17 393 views
-1

當我運行這個主要功能,後「系統(」暫停「);」程序退出並返回值:3221226356.有沒有人可以告訴我爲什麼? 主:進程退出返回值:3221226356

int main(int argc, char** argv) 
{ 
    int righe, colonne; 

    cout<<"-> Rows : "; 
    cin>>righe; 
    cout<<"-> Columns: "; 
    cin>>colonne; 

    Matrice<int> matrice(righe,colonne); 
    //no problems if declared as pointer 
    /*Matrice<int> *matrice; 
    matrice = new Matrice<int>(righe,colonne);*/ 

    delete &matrice; 
    //delete matrice; 
    system("PAUSE"); 
    return 0; 
} 

我有這個C++類:

template <typename T> 
class Matrice{ 
private: 
    int righe; 
    int colonne; 
    T **elementi; 

public: 
    Matrice(int righe, int colonne); 
}; 

的調用的構造函數:

template <typename T> 
Matrice<T>::Matrice(int r, int c) 
{ 
    righe = r; 
    colonne = c; 

    elementi = new T*[righe]; 
    for(int i=0;i<righe;i++) elementi[i] = new T[colonne]; 
} 

被叫析構函數:

template <typename T> 
Matrice<T>::~Matrice() 
{ 
    for(int i=0; i<righe; i++) delete[] elementi[i]; 
    delete[] elementi; 
    delete &righe; 
    delete &colonne; 
} 

如果我聲明我目的作爲指針並不存在問題!

+0

是否'Matrice'有析構函數?如果是這樣,它是如何編碼的? – NathanOliver

+0

編輯問題! – 2017-10-17 17:56:27

+0

你怎麼知道程序退出3221226356? – 2017-10-17 17:57:28

回答

1

你並不需要顯式解除分配righecolonne。當對象被銷燬時,它們會自動釋放。 刪除這些行:

delete &righe; 
    delete &colonne; 
+0

我解決了這個問題。謝謝! –

0

你不應該刪除任何靜態分配,e.g(rightecolonnematrice)這些對象應被自動刪除,當他們離開的範圍。

手動刪除對象將導致雙重缺失和失敗時的程序,這是不太相關system("PAUSE")在我看來。

delete運營商的樣本用法是:

int main(){ 
    int a; 
    // Don't need to delete, delete &a cause problem 
    int * b = new int; 
    delete b; //Need to delete 
}