Whether the destructor should be declared as a virtual function

If the derived class inherits the base class, and there is a base class pointer to the derived class object, then the destructor should be declared as a virtual function.

If the destructor is not a virtual function, a pointer to the base class of a derived class object, when the object is destroyed, the constructor of the base class will be called instead of the destructor of the derived class, which may cause memory leaks.
Why does this call the constructor of the base class? Because, if the destructor is not a virtual function, the function actually called during destructuring will be determined as the destructor of the pointer type class during compilation, that is, the destructor of the base class.

If the destructor is a virtual function, it points to the base class pointer of the derived class object. When the object is destroyed, the destructor function of the derived class will be called, and the destructor function of the derived class will automatically call the destructor function of the base class. This can avoid Memory leak.
Why does this call the constructor of the derived class? Because, declared as the destructor of the virtual function, the address of the function actually executed during the destructuring is uncertain during compilation. At runtime, the function actually executed during the destructuring is calculated according to the virtual table pointer and the virtual function table. Address, that is, the address of the destructor of the derived class.
Why is the address of the destructor of the derived class calculated in this way? Because the virtual table pointer is owned by every derived class object and points to the virtual function table of the derived class, the virtual function table of the derived class stores the address of the destructor declared as a virtual function.

Is it true that all destructors of classes must be declared as virtual functions? No, if a class does not have a derived class, or the class is a base class and has a derived class, but the base class pointer points to the derived class object, there is no need to declare the destructor of this class as virtual function. If it is declared as a virtual function, there will be more process of checking the virtual function table during destructuring, and more virtual function tables and virtual table pointers must be maintained in the memory, which will increase the overhead.

Guess you like

Origin blog.csdn.net/wx_assa/article/details/107844125