在没有内存泄漏的情况下处置学生

Dan*_*Leo 1 c++ oop

我有一个程序 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)

bol*_*lov 6

你能帮我写析构函数吗?

是的,给你:

最好的析构函数是您没有编写的析构函数,即您让编译器为您生成它。这应该是默认值。你应该很少 - 接近从不手动管理 C++ 中的资源。

您应该阅读三/五/零规则

零规则

具有自定义析构函数、复制/移动构造函数或复制/移动赋值运算符的类应专门处理所有权(遵循单一职责原则)。其他类不应具有自定义析构函数、复制/移动构造函数或复制/移动赋值运算符。

此规则也出现在 C++ 核心指南中作为C.20:如果您可以避免定义默认操作,请执行.

在某些情况下(想想诸如FLTK之类的GUI 工具包)您需要编写一个显式析构函数,但在大多数情况下您不需要。


Sie*_*ch0 5

当 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)