c++primer:
一个基类总是需要析构函数,而且它能将析构函数设定为虚函数。此时,该析构函数为了成为虚函数而令内容为空。
也就是说虚析构函数一定是这样的形式喽?
virtual ~Deconst()=default;
难道就不能有{ }包围的函数体吗?
PHP中文网2017-04-17 13:10:43
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的析构函数多半不会调用
//导致可能的资源/内存泄漏。
}
ringa_lee2017-04-17 13:10:43
No, you have explicitly defined the default destructor as your destructor. If you want to customize it, it will not be default
大家讲道理2017-04-17 13:10:43
=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() {}