当您有一个二维数组(C++)时调用析构函数的正确方法是什么?
What's the proper way to call a destructor when you have a two-dimensional array (in C++)?
这是我的构造函数:
Matrix::Matrix(int rows, int columns)
{
elements = new int*[rows];
for (int x = 0; x < rows; x++)
{
elements[x] = new int[columns];
}
}
这是我的析构函数:
Matrix::~Matrix()
{
delete elements;
}
我把析构函数改成了"delete[]elements"、"delete*elements"、"delete elements*",各种组合和每个组合都会冻结程序。我也尝试过"删除这个",但这也冻结了程序。我会尝试"free()",但我听说这是一种糟糕的编程实践,而且它实际上并没有释放内存。
感谢您的帮助。
这使我在valgrind --leak-check=yes
中没有泄漏
编辑:添加了一个复制构造函数以允许Matrix myMat2 = myMat;
样式的调用。到目前为止,您可能正在寻找swap
样式的函数和复制赋值运算符。等等等等…
#include <iostream>
class Matrix
{
int** elements;
int rows_;
public:
Matrix(int, int);
~Matrix();
Matrix(const Matrix&);
};
Matrix::Matrix(int rows, int columns)
{
std::cout<< "Matrix constructor called" << std::endl;
rows_ = rows;
elements = new int*[rows];
for (int x=0; x<rows; x++)
{
elements[x] = new int[columns];
}
}
Matrix::~Matrix()
{
for (int x=0; x<rows_; x++)
{
delete[] elements[x];
}
delete[] elements;
std::cout<< "Matrix destructor finished" << std::endl;
}
Matrix::Matrix(const Matrix &rhs)
{
std::cout<< "Called copy-constructor" << std::endl;
rows_ = rhs.rows_;
columns_ = rhs.columns_;
elements = new int*[rows_];
for (int x=0; x<rows_; x++)
{
elements[x] = new int[columns_];
*(elements[x]) = *(rhs.elements[x]);
}
}
int main()
{
Matrix myMat(5, 3);
Matrix myMat2 = myMat;
return 0;
}
Valgrind输出:
user:~/C++Examples$ valgrind --leak-check=yes ./DestructorTest
==9268== Memcheck, a memory error detector
==9268== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==9268== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==9268== Command: ./DestructorTest
==9268==
Matrix constructor called
Called copy-constructor
Matrix destructor finished
Matrix destructor finished
==9268==
==9268== HEAP SUMMARY:
==9268== in use at exit: 0 bytes in 0 blocks
==9268== total heap usage: 12 allocs, 12 frees, 200 bytes allocated
==9268==
==9268== All heap blocks were freed -- no leaks are possible
==9268==
==9268== For counts of detected and suppressed errors, rerun with: -v
==9268== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
你应该听从@chris的建议。但如果你想知道怎么做:
for (int i = 0; i < rows; i++)
{
delete[] elements[i];
}
delete[] elements;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- C++:使用方法调用析构函数的顺序是什么?
- 在析构函数中删除单链表的正确方法是什么?
- 哪种方法更适合处理虚拟析构函数?
- 显式调用 typedef'd 类类型的析构函数的正式正确方法
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 链表的析构函数方法
- 从C++中的虚拟析构函数调用虚拟方法
- 是在 C 或 C++ 析构函数中模拟 GO 语言 defer 的实用方法
- 这是删除析构函数中的数组的正确方法吗?
- 在其赋值运算符方法中调用对象的析构函数
- 抛出可由C++98和C++1x编译的析构函数.有更好的方法吗
- C++虚拟析构函数导致调用基方法
- 类具有虚拟方法,但具有非虚拟析构函数C++
- 从析构函数停止线程的正确方法
- 从基类析构函数调用派生类方法
- 如何通过析构函数方法删除对象(类)
- 使用共享指针时是否需要设置析构函数方法
- 如何理解CPP中的调用析构函数方法
- 需要从c++中的派生类调用基类析构函数方法