C++动态数组析构函数错误
C++ Dynamic array destructor error
我有一个包含行和列的稀疏矩阵类。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
类实现赋值运算符,并使用相同的技术(复制/交换)使其保持简单。
相关文章:
- 不命名构造函数和析构函数上的类型错误
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 矢量擦除调用的错误析构函数
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 导致堆缓冲区错误的动态分配数组的析构函数
- 非默认析构函数会导致不完整的类型错误
- 析构函数删除错误的元素
- 使用自定义工具集获取动态退出析构函数链接错误 - eh 矢量析构函数
- 使用 boost::thread 运行函子,但析构函数被错误地调用
- 错误 c++ 在令牌之前'('预期的构造函数、析构函数或类型转换
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 模板类中的析构函数给出错误
- 在析构函数内取消引用指针时出现分段错误
- 模板化子类析构函数中的隔离错误
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 获取错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换
- 显式调用类的析构函数时出现错误
- C++析构函数调用了错误的对象