我知道手動釋放是不好的做法,所以我不想這樣做。有沒有一種讓班級釋放自己的好方法?我寫了一個製作模板矩陣的程序,並重載了構造函數。我現在要使用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_;
}
使用'std :: vector'來代替自己管理數組內存。 –
對不起,我忘了提及我必須在這裏使用數組。我知道這是不好的做法,但我不允許使用矢量 –
對析構函數的更正:'delete [] array_;' – user4581301