强制对象 deallocate/go 超出范围以调用析构函数
Forcing object to deallocate/go out of scope to call destructor
我知道手动解除分配是不好的做法,所以我不想那样做。有什么好方法可以让 class 自行释放?我编写了一个制作模板矩阵的程序,并重载了复制构造函数。我现在想使用复制实现移动 contructor/operator,然后释放参数中给出的矩阵。
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_;
}
要使用 "move" 语义,请将相关数据从正在移动的对象移动到正在构建的对象。
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_;
}
}
我知道手动解除分配是不好的做法,所以我不想那样做。有什么好方法可以让 class 自行释放?我编写了一个制作模板矩阵的程序,并重载了复制构造函数。我现在想使用复制实现移动 contructor/operator,然后释放参数中给出的矩阵。
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_;
}
要使用 "move" 语义,请将相关数据从正在移动的对象移动到正在构建的对象。
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_;
}
}