Error: double free or corruption (fasttop) - Caused by destructor, but how?
Error: double free or corruption (fasttop) - Caused by destructor, but how?
我确切地知道错误是在哪里引起的,我想我什至可能知道原因——但我不知道是什么原因造成的:
房间
// room.hpp
#include "linkedlist.hpp"
#include "item.hpp"
class item;
class Room {
public:
Room();
private:
LinkedList<Item> itemsInThisRoom_;
};
-
// room.cpp
#include "room.hpp"
#include <iostream>
Room::Room() {
itemsInThisRoom_ = LinkedList<Item>();
};
链表
// linkedlist.hpp
//====================
// Class (Declaration)
template<class T> struct LinkedList {
public:
LinkedList();
~LinkedList();
private:
Node<T>* head_;
};
//====================
// Class (Instantiation)
template<class T> LinkedList<T>::LinkedList() {
head_ = new Node<T>;
size_= 0;
};
template<class T> LinkedList<T>::~LinkedList() { delete head_; };
main.cpp
#include <iostream>
#include "room.hpp"
#include "linkedlist.hpp"
int main() {
Room room;
return 0;
};
错误是在调用 Room 的 析构函数 时调用的——并且仅当我初始化一个房间对象时。这很好用:
#include <iostream>
#include "room.hpp"
#include "linkedlist.hpp"
int main() {
Room* room;
return 0;
};
此外,我可以 construct/destruct 个 LinkedList 的实例本身没有问题。我认为 'head_' 不知何故被删除了两次,但我不知道如何删除。
(有人建议我开始使用 std::unique_ptr 而不是 new/delete,我将开始这样做,但我只是想弄清楚为什么这会导致错误!!)
您手动管理内存,这意味着您还需要实现赋值运算符和复制构造函数。
现在,当您复制对象时:itemsInThisRoom_ = LinkedList<Item>();
,您在堆栈对象 (LinkedList<Item>();
) 被删除时释放了内存,但 itemsInThisRoom 仍然指向它。
因此,当它被销毁时,它会尝试删除堆栈对象中已经删除的内存。
我确切地知道错误是在哪里引起的,我想我什至可能知道原因——但我不知道是什么原因造成的:
房间
// room.hpp
#include "linkedlist.hpp"
#include "item.hpp"
class item;
class Room {
public:
Room();
private:
LinkedList<Item> itemsInThisRoom_;
};
-
// room.cpp
#include "room.hpp"
#include <iostream>
Room::Room() {
itemsInThisRoom_ = LinkedList<Item>();
};
链表
// linkedlist.hpp
//====================
// Class (Declaration)
template<class T> struct LinkedList {
public:
LinkedList();
~LinkedList();
private:
Node<T>* head_;
};
//====================
// Class (Instantiation)
template<class T> LinkedList<T>::LinkedList() {
head_ = new Node<T>;
size_= 0;
};
template<class T> LinkedList<T>::~LinkedList() { delete head_; };
main.cpp
#include <iostream>
#include "room.hpp"
#include "linkedlist.hpp"
int main() {
Room room;
return 0;
};
错误是在调用 Room 的 析构函数 时调用的——并且仅当我初始化一个房间对象时。这很好用:
#include <iostream>
#include "room.hpp"
#include "linkedlist.hpp"
int main() {
Room* room;
return 0;
};
此外,我可以 construct/destruct 个 LinkedList 的实例本身没有问题。我认为 'head_' 不知何故被删除了两次,但我不知道如何删除。
(有人建议我开始使用 std::unique_ptr 而不是 new/delete,我将开始这样做,但我只是想弄清楚为什么这会导致错误!!)
您手动管理内存,这意味着您还需要实现赋值运算符和复制构造函数。
现在,当您复制对象时:itemsInThisRoom_ = LinkedList<Item>();
,您在堆栈对象 (LinkedList<Item>();
) 被删除时释放了内存,但 itemsInThisRoom 仍然指向它。
因此,当它被销毁时,它会尝试删除堆栈对象中已经删除的内存。