[英]What's the proper way to declare and initialize a (large) two dimensional object array in 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.