Do we need a virtual destructor for a classes which are gonna be used in Qt-way: set QObject
-parent which will call in QObject's destructor deleteLater()
or something like that for any object for which it was set as parent?
For example:
class MyWidget : public QWidget {
public:
MyWidget() {
w = new QWidget(this);
// "w" will be deleted automatically by parent MyWidget::QWidget::QObject's destructor afaik
}
private:
QWidget *w;
}
Do we need a virtual destructor for MyWidget
class if it is gonna be inherited? I see no reason for this because it does not delete anything and each property of the class which is derived from QObject
will be deleted from MyWidget::QWidget::QObject 's destructor.
如果您添加或不添加它并不重要,因为QWidget
继承的QObject
具有虚拟析构函数,并且它在整个层次结构中传播。
You don't need to explicitly write an (empty) virtual
destructor because QWidget
already marks its distructor as virtual
, so automatically all destructors of the class hierarchy are virtual
.
But in general, if you write a class that is going to be inherited (and doesn't already have a base class with a virtual
destructor), always specify a virtual
destructor, otherwise things will blow up badly if anyone tries to destroy an object of your class hierarchy through a pointer of the base class type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.