乐闻世界logo
搜索文章和话题

When should you not use virtual destructors?

1个答案

1

In C++, virtual destructors are typically used in base classes to ensure that derived class objects deleted through a base class pointer correctly invoke the derived class destructor. As a key aspect of polymorphic behavior, virtual destructors guarantee proper resource cleanup for derived classes even when only a base class reference or pointer is available.

The following scenarios are when virtual destructors should not be used:

  1. Non-polymorphic base classes: If a class is not intended to serve as a base class or does not require polymorphic behavior from its derived classes, declaring the destructor virtual is unnecessary. This is due to the overhead introduced by virtual functions, specifically the virtual table (vtable). When the class is not designed for polymorphism (i.e., not accessed via base class pointers to manipulate derived objects), virtual destructors should be avoided.

    Example:

    cpp
    class NonPolymorphic { int data; public: ~NonPolymorphic() { // Non-virtual destructor // Clean up resources } };
  2. Performance-critical code: When performance is a key consideration, if the performance overhead from the additional indirection layer (via the virtual table) is unacceptable, virtual destructors should be avoided. In embedded systems or real-time environments where every clock cycle is valuable, virtual destructors may need to be omitted.

  3. Small objects or frequently created and destroyed objects: For very small objects or those requiring frequent creation and destruction, maintaining a virtual table pointer per object may incur significant memory overhead. In such cases, avoiding virtual destructors is more efficient if polymorphism is not required.

    Example:

    cpp
    class SmallObject { char data[10]; public: ~SmallObject() { // Non-virtual destructor // Quick cleanup, no polymorphism needed } };

Summary: Virtual destructors are a crucial aspect of polymorphic class design, ensuring proper cleanup for derived objects managed through base class pointers. However, if the class is not designed for polymorphism or in specific scenarios where the additional overhead is unreasonable, they should be avoided to maintain code conciseness and efficiency.

2024年6月29日 12:07 回复

你的答案