首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当您有一个二维数组(在C++中)时,调用析构函数的正确方法是什么?

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

Stack Overflow用户
提问于 2014-08-27 02:03:44
回答 2查看 4.9K关注 0票数 1

这是我的构造函数:

代码语言:javascript
复制
Matrix::Matrix(int rows, int columns)
{
  elements = new int*[rows];
  for (int x = 0; x < rows; x++)
  {
    elements[x] = new int[columns];
  }
}

这是我的破坏者

代码语言:javascript
复制
Matrix::~Matrix()
{
    delete elements;
}

我已经将析构函数更改为“删除[]元素”、“删除*元素”、“删除元素*”,所有类型的组合和每个组合都会冻结程序。我也尝试过“删除这个”,但这也冻结了程序。我会尝试" free ()“,但我听说这是糟糕的编程实践,它实际上并没有释放内存。

任何帮助都是非常感谢的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-27 02:23:07

这使我没有泄露valgrind --leak-check=yes的信息

编辑:添加了一个副本构造函数,以允许Matrix myMat2 = myMat;样式调用。此时,您可能需要寻找一个swap样式的函数和一个副本赋值操作符。等等等等..。

代码语言:javascript
复制
#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;
}

瓦兰产出:

代码语言:javascript
复制
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)
票数 4
EN

Stack Overflow用户

发布于 2014-08-27 02:10:35

你应该听从克里斯的建议。但如果你想知道怎么做

代码语言:javascript
复制
for (int i = 0; i < rows; i++)
{
    delete[] elements[i];
}

delete[] elements;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25517847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档