Home >Backend Development >C++ >Should a Pure Virtual Destructor in C Be Implemented?
When defining an abstract base class in C , it may be tempting to declare a virtual destructor as purely virtual, as shown in the code snippet below:
class A { public: virtual ~A() = 0; };
While this syntax is valid in certain compilers, such as MSVC, it poses a lurking hazard that can lead to runtime crashes.
The issue with the code above is that the virtual destructor is declared to be pure without providing an implementation. This means that the destructor's behavior is delegated to concrete derived classes. However, if an object of type A itself is ever destroyed, its destructor will be called, and its lack of implementation will result in undefined behavior.
In a typical scenario, deriving from the abstract base class A and attempting to destroy an object of the derived class will ultimately invoke A's destructor. Without an implementation, this can trigger undefined behavior on certain platforms, such as invoking the purecall handler and crashing the program.
To resolve this issue, the abstract base class's destructor should be implemented explicitly, even if its body is empty. The corrected code snippet below demonstrates this:
class A { public: virtual ~A() = 0; }; inline A::~A() { }
By providing an empty implementation for A's destructor, you ensure that its behavior is defined when called directly or through derived classes.
The above is the detailed content of Should a Pure Virtual Destructor in C Be Implemented?. For more information, please follow other related articles on the PHP Chinese website!