2015-09-10 43 views
0

我知道手動釋放是不好的做法,所以我不想這樣做。有沒有一種讓班級釋放自己的好方法?我寫了一個製作模板矩陣的程序,並重載了構造函數。我現在要使用copy來實現移動構造器/操作符,然後釋放參數中給出的矩陣。強制對象釋放/超出範圍調用析構函數

template <typename T> 
class matrix 
{ 
    private: 
     int cols; 
     int rows; 
     T **array_;  //pointer to array of pointers 
    public: 
     ~matrix(); 

     matrix <T> & operator=(const matrix <T> & matr){ 
      CopyMatrix(matr);  //copy, not move 
      return *this;   //matr still exists 
     } 

     matrix<T>(matrix<T> && matr){  //move contructor 
      CopyMatrix(matr); 
      delete matr.array_;  //will this work? 
     } 

     matrix <T> & operator=(matrix<T> && matr){ //move operator 
      CopyMatrix(matr); 
      delete matr.array_;  //will this work? 
      return *this; 
     } 
} 


template <typename T> 
matrix <T>::~matrix(){ 
    for (int i = 0; i < rows; i++){ 
     delete [] array_[i]; 
    } 
    delete array_; 
} 
+2

使用'std :: vector'來代替自己管理數組內存。 –

+0

對不起,我忘了提及我必須在這裏使用數組。我知道這是不好的做法,但我不允許使用矢量 –

+0

對析構函數的更正:'delete [] array_;' – user4581301

回答

1

要使用「移動」語義,請將相關數據從正在移動的對象移至正在構建的對象。

matrix<T>(matrix<T> && matr) : cols(matr.cols), 
           rows(matr.rows), 
           array_(matr.array_) // Move the ownership of the data to the new object. 
{ 
    matr.array_ = nullptr; // matr does not own the data any longer. 
} 

然後,確保析構函數正確地處理它。

template <typename T> 
matrix <T>::~matrix(){ 
    if (array_ != nullptr) 
    {  
     for (int i = 0; i < rows; i++){ 
      delete [] array_[i]; 
     } 
     delete array_; 
    } 
} 
+0

對不起,我覺得真的很愚蠢,我還是這個新手。非常感謝 –

+1

@是的,我不覺得糟糕。我們都在學習新東西的同時經歷這些階段。 –

相關問題