【发布时间】:2018-03-27 07:03:06
【问题描述】:
我正在学习使用链表实现 Stack。这是节点类:
class StudentInfo {
public:
string id, name, course;
double GPA;
StudentInfo *next;
};
这是 Stack 类:
class StackLinkedList {
public:
StudentInfo* top; //pointer to point to the top node
int size; //variable to keep the size of the stack
//constructor
StackLinkedList() {
this->size = 0;
this->top = NULL;
}
//destructor
~StackLinkedList() {
StudentInfo *current = top;
while (top) {
current = current->next;
delete top;
top = current;
}
}
//to add item into stack - push on top
void push(StudentInfo *newStudent) {
if (!top) {
top = newStudent;
return;
}
newStudent->next = top;
top = newStudent;
size++;
}
void main() {
StudentInfo s1("phi", "123", "computer science", 4.0);
StudentInfo s2("abc", "123", "software engineer", 4.0);
StudentInfo s3("zxc", "123", "business management", 4.0);
StackLinkedList list;
StudentInfo *ptr;
ptr = &s1;
list.push(ptr);
ptr = &s2;
list.push(ptr);
ptr = &s3;
list.push(ptr);
};
当我尝试在 push() 和 printAll() 上运行单元测试时,一切正常。但是,在调用 destructor() 后,出现错误 Debug Assertion Failed … is_block_type_valid(header-> _block_use)。并且调试器在delete top;触发了断点
//destructor
~StackLinkedList() {
StudentInfo *current = top;
while (top) {
current = current->next;
delete top; //here
top = current;
}
}
如果我把top = NULL; 放在delete top; 之前,错误就消失了。所以,我对top = NULL; 声明有点困惑。
编辑:NodeType 的构造函数
StudentInfo(string id, string name, string course, double gpa) {
this->id = id; this->name = name; this->course = course; this->GPA = gpa; this->next = NULL;
}
【问题讨论】:
-
首先,尝试运行 valgrind 并检查是否有任何内存泄漏。
-
1) 不要使用原始的
new/delete。使用智能指针(或只是对象的普通容器)。 2) 不要使用NULL。使用nullptr。 -
@JesperJuhl 如果我尝试为指针返回类型返回 nullptr 是否有效?
-
@Phi Truong 你可以返回
nullptr,当然。这是否是您想要以及您的呼叫者期望是另一个问题。
标签: c++ constructor linked-list aggregate destructor