c++ - 虚析构函数的内容一定要为空吗?
PHPz
PHPz 2017-04-17 13:08:43
0
3
645

c++primer:

一个基类总是需要析构函数,而且它能将析构函数设定为虚函数。此时,该析构函数为了成为虚函数而令内容为空。

也就是说虚析构函数一定是这样的形式喽?

virtual ~Deconst()=default;

难道就不能有{ }包围的函数体吗?

PHPz
PHPz

学习是最好的投资!

reply all(3)
Ty80

The person above made it clearer. Default will ask the compiler to add a {} for you.
If your class holds some resources, the virtual destructor should not be empty,
needs to do some cleanup work. For example:

class A{
public:
    virtual ~A(){
        free(handle);
        delete ptr;
    }
    
    someFilehandle* handle;
    somePointer* ptr;   
};

If A is used as a parent class, then its destructor should be declared as virtual as much as possible to avoid
the following situations:

class B : public A {
public:
    //some declaration
    virtual ~B() {}
};

//假使你获得了或者创建了一个A*类型的指向一个B*对象
{
    A* a = new B();
    delete a;//如果A的构造函数不是virtual,那么这个时候
             //就是一个未定义行为,B的析构函数多半不会调用
             //导致可能的资源/内存泄漏。
}
左手右手慢动作

No, you have explicitly defined the default destructor as your destructor. If you want to customize it, it will not be default

大家讲道理

=default is not empty, but the default behavior is used, or the destructor of the member is called. This is not essentially different from writing {} directly.

virtual ~Deconst()=default;
virtual ~Deconst() {}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!