下面是一个关于动态内存分配和对象创建的 C++ 练习。基本上 - 一个自定义类 Student 和一个自定义类 Group,它在内部保留指向 Students 的指针数组。显然 Group 的析构函数存在问题,但我花了数小时阅读手册和浏览论坛,但仍然无法理解我做错了什么。
欢迎任何评论。
UPD:问题是 - 退出时出错。 “调试断言失败..._BLOCK_TYPE_IS_VALID...”
class Student{
char *firstName;
char *lastName;
public:
Student(): firstName(NULL), lastName(NULL){}
Student(const char *fname, const char *lname){
firstName = new char[32];
lastName = new char[32];
strcpy_s(firstName, 32, fname);
strcpy_s(lastName, 32, lname);
}
void Show(){
cout << firstName << " " << lastName << endl;
}
~Student(){
if(lastName != NULL)
delete[] lastName;
if(firstName != NULL)
delete[] firstName;
}
};
class Group{
Student *students;
int studentCounter;
public:
Group(){
students = NULL;
}
Group(const int size){
students = new Student[size];
studentCounter = 0;
}
void Push(Student *student){
students[studentCounter] = *student;
studentCounter++;
}
void ShowAll(){
for(int i = 0; i < studentCounter; i++){
students[i].Show();
}
}
~Group(){
if(students != NULL)
delete[] students; //problem here?
}
};
void main(){
Student jane("Jane", "Doe");
Student john("John", "Smith");
Group group(2);
group.Push(&jane);
group.Push(&john);
group.ShowAll();
_getch();
}
最佳答案
您的学生类(class)缺少 copy assignment Operator ,在没有它的情况下,提供的默认赋值运算符仅执行 shallow copy .
当您创建学生对象并插入 Group 时,学生对象和 Group 在其数组中保存的对象在没有赋值运算符的情况下具有对 firstName 和 lastName 数组的相同引用,这应该创建一个这些数据结构的克隆。
因此,当学生对象在 stack unwinding 期间被删除时, 结果是 double delete因为数组在 Group 被销毁时已经被删除。
关于C++解构指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937402/