我有一个程序 Student 。OOP Student ,我编写了构造函数,但我不知道如何析构 Student 因为我使用 string 而不是 char* 作为学生姓名
这是我的课。构造函数已经运行。你能帮我写析构函数吗?因为学生姓名数据类型是字符串所以我不能使用delete[]this->m_Sname.
class Student {
private:
string m_Sname; //Student Name
double m_SMathPoint; //Student Math Point
double m_SLiPoint; //Student Literature Point
public:
Student(string, double, double); //Initialize a student with name, math, literature points
Student(string); //Initialize a student with name, math = literature = 0.
Student(const Student& s); //Initialize a student from another student
~Student(); //Depose a student without memory leak
void printStudent();
};
Run Code Online (Sandbox Code Playgroud)
当 Student 退出作用域或由于 RAII (Resource Acquisition Is Initialization) 的机制而被销毁时,std::string 将自动释放它消耗的内存。基本上,当一个变量的生命周期结束时,无论是通过它隐式地离开作用域还是以其他方式被销毁,它的析构函数将被调用,然后它所有成员的析构函数将被调用(除非这些成员是哑指针或对数据的引用,则必须手动释放它们)。因此,当销毁学生变量时,将隐式调用 m_Sname 的析构函数。
正如 cigien 在对您的帖子的评论中所述,只需删除您对析构函数的定义,或者,如果您希望明确,您可以说类似~Student() = default;,这将完成同样的事情。
如果我还不清楚,这里有一些代码:
void f()
{
Student john("John", 0.75, 0.75); // Constructor
Student *betty = new Student("Betty", 0.8, 0.7);
...
// john is about to leave the scope
// the scope being the end of function 'f'
// john's destructor will automatically be called.
// betty's destructor will not be called unless manually destroyed
// by doing 'delete betty;'
//
// ~Student() for 'john' is here - the string stored inside 'john' will also
// be freed when john is freed.
// ~Student() for 'betty' is NOT here. The pointer would have to be freed
// or a memory leak will occur.
}
Run Code Online (Sandbox Code Playgroud)