提问者:小点点

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


我有个项目学生。 OOP学生,我写了构造函数,但是我不知道如何析构一个学生,因为我用string代替Char*作为学生名

这是我的课。 构造函数已运行。 你能帮我写析构函数吗? 因为Student name数据类型是string,所以我不能使用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();
};

共2个答案

匿名用户

你能帮我写析构函数吗?

是的,给你:

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

你应该读三/五/零规则:

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

这条规则也出现在C++核心指南中,作为C.20:如果您可以避免定义默认操作,那么就这样做。

在某些情况下(想想像FLTK这样的GUI工具包),您需要编写显式析构函数,但在大多数情况下,您不需要编写显式析构函数。

匿名用户

Std::String将在学生退出作用域或由于RAII(资源获取即初始化)机制而被破坏时自动释放它所消耗的内存。 基本上,当一个变量的生命周期结束时,无论是通过它隐式地离开作用域,还是通过其他方式被销毁,都会调用它的析构函数,然后调用它的所有成员的析构函数(除非这些成员是哑指针或数据引用,否则必须手动释放它们)。 因此,在销毁学生变量时,将隐式调用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.
}