Defining Pure Virtual Destructors in C : Unveiling the Pitfalls
The concept of pure virtual destructors in C raises important questions regarding the correct implementation for abstract base classes. Consider the following code snippet:
class A { public: virtual ~A() = 0; };
The question arises as to whether this approach is appropriate for defining an abstract base class. While it compiles successfully in MSVC, concerns exist that it may result in runtime crashes.
Unveiling the Problem
The issue stems from the lack of implementation for the pure virtual destructor. When derived classes are created from A, their destructors will eventually invoke A's destructor. However, since A's destructor is pure, the call will result in undefined behavior.
Resolving the Pitfall
To avoid this runtime crash, it is essential to implement the destructor in the base class itself. A simple inline implementation, as shown below, will suffice:
class A { public: virtual ~A() = 0; }; inline A::~A() { }
This implementation ensures that when any derived class is deleted or destroyed, A's destructor will be called and the program will behave as expected.
The above is the detailed content of Should Pure Virtual Destructors in C Be Defined?. For more information, please follow other related articles on the PHP Chinese website!