Pure Virtual Destructors in C
In the world of object-oriented programming, abstract base classes often require pure virtual destructors. However, concerns arise when writing code like this:
class A { public: virtual ~A() = 0; };
This raises the question of whether it's acceptable for an abstract base class to have a purely virtual destructor. While Microsoft Visual C compiles it without issue, what happens at runtime?
The answer is: Undefined behavior. If an instance of a class derived from A is deleted or destroyed, A's destructor will be invoked. However, since it's purely virtual and lacks an implementation, this triggers undefined behavior. On certain platforms, this can result in the purecall handler being invoked, leading to a crash.
To avoid this, it's crucial to implement the destructor as well. A minimal implementation like this should suffice:
class A { public: virtual ~A() = 0; }; inline A::~A() { }
This way, when instances of derived classes are deleted, A's destructor won't cause undefined behavior.
The above is the detailed content of Should Abstract Base Classes in C Have Pure Virtual Destructors?. For more information, please follow other related articles on the PHP Chinese website!