因此,在我的代码中,我有类Student,该类的矢量是* ModuleGrade类的对象。我在Student类中有一个析构函数,但随后在=运算符的重载中也有一个析构函数。我是否需要两次都使用它,还是可以将析构函数保留在Student类中,所以它在=运算符的重载中也可以完成此工作。我希望我能解释一下。
编辑:我知道一个事实,如果向量不带*会更好,但是这样做的目的是让我证明我了解*和深层复制构造函数是如何工作的。
这是我的代码:
学生
private:
int studentNumber;
vector <ModuleGrade*> gradeList;
public:
~Student();
Student(const Student& student); // user-defined copy ctor
Student& operator = (const Student& student);
学生.cpp
Student::~Student()
{
int number = gradeList.size();
for(int i= 0; i<number; i++){
delete gradeList[i];
}
}
Student::Student(const Student &student ) : Person(student) {
//deep copy constructor
this->studentNumber=student.studentNumber;
int size = student.gradeList.size();
for(int i=0; i <size; i++) {
// ModuleGrade *m ;
ModuleGrade *mg = new ModuleGrade(*(student.gradeList[i]));
gradeList.push_back(mg);
}
}
Student& Student :: operator = (const Student & student) {
if (&student == this) return *this;
Person :: operator=(student);
studentNumber = student.studentNumber;
//delete gradeList of this
//SHOULD I DO THIS IF THERE IS A DESTRUCTOR DECLARED???
for (unsigned int i=0; i<gradeList.size(); i++){
delete gradeList[i];
gradeList.clear();
}
//fill this with grades of student
for(unsigned int i=0; i<student.gradeList.size(); i++) {
ModuleGrade *m = new ModuleGrade(*(student.gradeList[i]));
gradeList.push_back(m);
}
return *this;
}
是的,如果您管理指针,则需要确保在分配和销毁时清除指向对象。
这就是为什么人们经常使用move和swap编写赋值运算符的原因:
X& operator=(X const& other){
X temp(other);
swap(temp);
return *this;
}
因为清理工作只需要写在析构函数中即可。swap
只是交换内容,而复制构造函数分配新内容。
使用移动交换还可以覆盖您编写的情况,x=x
否则,如果在尝试从另一个对象复制数据之前销毁了被分配给对象的数据,则需要在赋值运算符中明确测试该情况。目的。
同样,在实际代码中,您应该使用,std::unique_ptr
或者std::shared_ptr
如果您想通过指针来保存对象:您永远不必delete
手动编写,并且经常可以使用std::make_unique
或std::make_shared
代替new
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句