C++动态数组析构函数错误

C++ Dynamic array destructor error

本文关键字:错误 析构函数 数组 动态 C++      更新时间:2023-10-16

我有一个包含行和列的稀疏矩阵类。rows integer用于初始化动态数组中LinkedList的数字。

template<class T>
SM<T>::SM(int rows, int columns)
{
    this->rows = rows;
    this->columns = columns;
    this->rowList = new LinkedList<T>[rows];
    cout << "Going to create a sparse matrix of dimensions " << this->rows << "-" << this->columns << endl;
}

我还有这个复制构造函数稍后使用:

编辑:

LinkedList副本构造函数:

LinkedList(const LinkedList & other) {
    this->size = other.size;
    this->head = NULL;
    this->tail = NULL;
    NodeType<T> * current = other.head;
    while (current != NULL) {
        setValue(current->info, current->index);
        current = current->link;
    }
}

SparseMatrix副本构造函数:

template<class T>
SM<T>::SM(const SM<T> & other)
{
    this->rows = other.rows;
    this->columns = other.columns;
    this->rowList = new LinkedList<T>[this->rows];
    for (int i = 0; i < this->rows; i++)
    {
        rowList[i] = other.rowList[i];
    }
}

这是我的LinkedList析构函数和SparseMatrix析构函数:

~LinkedList() {
    cout << "Going to delete all " << size << " elements of the list." << endl;
    NodeType<T> * current = head;
    while (current != NULL) {
        current = current->link;
        delete head;
        head = current;
    }
}
template<class T>
SM<T>::~SM()
{
    cout << "Deleting sm" << endl;
    delete [] rowList;
    rowList = NULL;
}

然而,当我完成代码时。我得到一个析构函数错误。

这是我的main():

SM<int> sm(rows, columns);
SM<int> sm2(rows, columns);
SM<int> sm3 = sm2;

这就是错误:

_CrtIsValidHeapPointer

我是C++的新手,我真的不知道我的代码出了什么问题。我们非常感谢您的帮助。

一个问题是您的LinkedList类缺少assignment operator.,即

LinkedList<T>& operator=(const LinkedList<T>& other);

你需要这个函数的原因是,如果没有它,像这样的赋值(来自你的构造函数):

rowList[i] = other.rowList[i];

将创建浅层副本(复制内部指针值),这不是我们想要的。由于rowList[i]other.rowList[i]是独立的对象,它们内部必须有独立的指针。否则,rowList[i]other.rowList[i]的析构函数在对delete发出调用时将使用相同的指针值,从而导致未定义的行为。

让我们假设您的LinkedList复制构造函数和析构函数工作正常。实现赋值运算符的最简单方法是使用复制/交换idom:

#include <algorithm>
//...
LinkedList<T>& operator=(const LinekedList<T>& other)
{
   LinkedList<T> temp(other); // uses copy constructor
   std::swap(temp.size, size);
   std::swap(temp.head, head);
   std::swap(temp.tail, tail);
   return *this;
}

请注意,我们所做的只是创建一个临时成员,并用this交换临时成员中的所有成员,然后返回*this

请注意,您需要为SM类实现赋值运算符,并使用相同的技术(复制/交换)使其保持简单。