强制对象释放/离开作用域以调用析构函数

Forcing object to deallocate/go out of scope to call destructor

本文关键字:作用域 调用 析构函数 离开 对象 释放      更新时间:2023-10-16

我知道手动释放是不好的做法,所以我不想这样做。有没有一种好方法可以让一个类释放它自己?我写了一个生成模板矩阵的程序,并重载了复制构造函数。我现在想实现move构造函数/操作符,使用复制,然后释放在参数中给出的矩阵。

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_;
   }
}