【问题标题】:C++ Dynamic array destructor errorC++ 动态数组析构函数错误
【发布时间】:2016-04-02 23:11:24
【问题描述】:

我有一个带有行和列的稀疏矩阵类。行整数用于初始化动态数组中的多个 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&lt;T&gt; 实现了有效的复制赋值运算符?
  • 您正在调用函数readElementsprintMatrix。如果这些函数对问题没有影响,请删除它们并重新运行您的代码。否则,发布这些函数。
  • 另外,LinkedList 的析构函数是做什么的?如果它还遍历链接(因此删除一个也会删除所有链接的节点),那么您不应该在SM 的析构函数中明确地这样做。删除一个对象两次会产生未定义的行为。
  • 让我们看看您的LinkedList 用户定义的复制构造函数和赋值运算符。这条线最好有一个赋值运算符才能正常工作:rowList[i] = other.rowList[i];
  • @Kelok Chan 你应该分享一个简短的、独立的、正确的(可编译的)程序,这将使你很容易理解你面临的问题。

标签: c++ constructor destructor copy-constructor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 2015-06-09
    • 2013-03-20
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2015-12-31
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多