【发布时间】:2013-12-08 09:31:51
【问题描述】:
我写了两个类:学生和课程。 Course 类在其主体中有一个 Student *students 作为数据成员。在我的顶级 StudentReviewSystem 中,我有一个 Course *courses 作为数据成员,并且我有一个 deleteCourse(const int courseId) 方法,它使用“courseId”删除课程并调整“课程”的大小。这是我的 deleteCourse 方法代码:
void StudentReviewSystem::deleteCourse(const int courseId){
int index = 0;
bool found = false;
//temp arr
Course *temp = new Course[courseSize];
for(int i = 0; i < courseSize && !found; i++){
if(courseId == courses[i].getCourseId()){
index = i;
found = true;
}
}
if(found){
temp = courses;
courses = new Course[courseSize-1];
for(int i = 0; i <= index-1;i++ ){
courses[i] = temp[i];
}
for(int i = index+1; i < courseSize; i++){
courses[i-1] = temp[i];
}
delete[] temp;
cout << "Course has been deleted!" << endl;
courseSize--;
}
}
当我尝试删除 temp 时,我得到一个“检测到 glibc”的错误,它下面有一个内存映射,然后是 aborted(core dumped) 错误。但是当我注释掉 delete[] temp; , 有用。你能帮帮我吗,我真的是 C++ 新手。
谢谢...
P.S:当我注释掉 ~Course(){ delete[] students;} 析构函数时,它再次起作用。我想我有一个非常愚蠢的问题,再次感谢您...
【问题讨论】:
-
您正在泄漏内存。
Course *temp = new Course[courseSize];在这段代码中总是被遗弃和泄露。这不是 Java。从表面上看,您的Course班级并没有练习Rule of Three根本。 -
用
std::vector或其他一些标准容器替换所有这些数组,并使用智能指针和标准算法 - 您可以将该函数减少到大约三行不包含原始新闻或删除的行。你在那里泄露了Course[courseSize]。如果学生可以属于几门课程,我怀疑你是在双重删除他们。
标签: c++ class object pointers memory-leaks