c++ - 当你有一个二维数组(在 C++ 中)时,调用析构函数的正确方法是什么?

标签 c++ arrays multidimensional-array destructor

这是我的构造函数:

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

我已将析构函数更改为说“删除 [] 元素”、“删除 * 元素”、“删除元素*”以及各种组合,并且每种组合都会卡住程序。我也试过“删除这个”,但这也卡住了程序。我会尝试“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)

关于c++ - 当你有一个二维数组(在 C++ 中)时,调用析构函数的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517847/

相关文章:

python - 在 C++ 中嵌入 Python。传递接收列表列表的字符串 vector

c - 使用较大数组初始化字符数组时的行为

javascript - 如何在jquery或js中创建动态二维数组

php - 数据库 : Matchmaking and Scoring between multiple columns (3D Data Set)

C++:生成未知深度的多维 vector

c++ - 如何创建一个新线程并在一段时间后终止它?

c++ - 二维字符数组中的字符设置不正确

c++ - 从单个数组的不同段初始化 Eigen::Vector

c++ - 跨模板特化共享的静态成员

c++ - 在 C++ 中从文本文件读取输入到数组