强制对象释放/离开作用域以调用析构函数
Forcing object to deallocate/go out of scope to call destructor
我知道手动释放是不好的做法,所以我不想这样做。有没有一种好方法可以让一个类释放它自己?我写了一个生成模板矩阵的程序,并重载了复制构造函数。我现在想实现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_;
}
}
相关文章:
- 是同一作用域的函数部分中的函数调用
- 在新作用域中使用unique_lock是否等效于在使用共享资源的工作结束时解锁调用
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 空的唯一指针在离开作用域时调用析构函数
- 类的堆分配对象是否在其作用域之后但在 C++ 中调用其析构函数之前处于活动状态
- 在提升作用域出口中调用对象函数
- 在调用函数的作用域中构造返回的对象
- gdb函数从本地作用域调用std::vector会导致错误
- 在作用域结束之前调用了析构函数
- ::c++中模板函数调用前面的作用域解析运算符
- 在对象超出作用域之前调用析构函数
- 为函数调用添加作用域
- 调用签名相同但作用域不同的方法
- 强制对象释放/离开作用域以调用析构函数
- 在c++中,没有变量名的构造函数调用的生存期/作用域是什么?
- 在包含作用域的函数调用期间持续的临时函数参数
- 未在作用域内声明的c++类——从main调用
- 在类作用域内定义方法时,除非在原始 cpp 文件中的其他位置调用方法,否则项目不会编译
- 在第三次调用中,当地址因本地作用域而被销毁时,temp2->next 如何能够访问第二个节点的地址?
- 离开作用域时没有调用析构函数