多型性解構函式

如果要以多型方式使用類,並將派生例項儲存為基本指標/引用,則其基類’解構函式應為 virtualprotected。在前一種情況下,這將導致物件破壞檢查 vtable,根據動態型別自動呼叫正確的解構函式。在後一種情況下,禁用通過基類指標/引用銷燬物件,並且只有在顯式地將物件視為其實際型別時才能刪除該物件。

struct VirtualDestructor {
    virtual ~VirtualDestructor() = default;
};

struct VirtualDerived : VirtualDestructor {};

struct ProtectedDestructor {
  protected:
    ~ProtectedDestructor() = default;
};

struct ProtectedDerived : ProtectedDestructor {
    ~ProtectedDerived() = default;
};

// ...

VirtualDestructor* vd = new VirtualDerived;
delete vd; // Looks up VirtualDestructor::~VirtualDestructor() in vtable, sees it's
           // VirtualDerived::~VirtualDerived(), calls that.

ProtectedDestructor* pd = new ProtectedDerived;
delete pd; // Error: ProtectedDestructor::~ProtectedDestructor() is protected.
delete static_cast<ProtectedDerived*>(pd); // Good.

這兩種實踐都保證派生類的解構函式將始終在派生類例項上呼叫,從而防止記憶體洩漏。