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

C++ Dynamic array destructor error

我有一个包含行和列的稀疏矩阵 class。 rows 整数用于初始化动态数组中的多个 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(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;
    }
}

稀疏矩阵复制构造函数:

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 class 缺少 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 复制构造函数和析构函数工作正常。实现赋值运算符的最简单方法是使用 copy / swap 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 class 实现赋值运算符,并使用相同的技术(复制/交换)保持简单。