【发布时间】:2014-05-02 14:07:27
【问题描述】:
void Set::remove(Set::Node* p) {
if(p == nullptr) return;
Node* tmp = p->next;
delete p;
return remove(tmp);
}
Set::~Set() {
remove(list);
}
class Set {
public:
~Set();
private:
struct Node {
int value;
Node* next;
};
Node* list;
}
Set& Set::operator= (const Set& other) {
if(this == &other) return *this;
list = copy(other.list);
sizeOfList = other.sizeOfList;
return *this;
}
Set::Node* Set::copy(Set::Node* list) {
if(list == nullptr) return nullptr;
return cons(list->value, copy(list->next));
}
Set::Node* Set::cons (int value, Set::Node* next) {
Node* tmp = new Node;
tmp->value = value;
tmp->next = next;
return tmp;
}
Set() : list(nullptr), sizeOfList(0) {};
我想测试析构函数,所以我手动调用它(在程序的最后一行)
x.~Set();
但后来我得到了对象 0x100103ad0 的 * 错误:未分配被释放的指针。我不知道我做错了什么。我已经阅读了尽可能多的相关帖子,但找不到解决方案。希望有人帮忙!
【问题讨论】:
-
你在某处分配内存吗?
-
如果你做对了,就会自动调用析构函数。永远不要自己打电话给他们。如果你需要,相信我,你会知道的。
-
你是说我的代码是正确的,但只是没有手动调用它?
-
在构造函数中将
Set::list设置为nullptr,还是未初始化? -
是的,它使用初始化列表将列表设置为 nullptr
标签: c++ pointers destructor