delete-non-virtual-dtor 問題解決辦法
阿新 • • 發佈:2019-01-05
編譯過程中出現如下警告:
warning: deleting object of abstract class type ‘CAN_driver’ which has non-virtual destructor will cause undefined behaviour [-Wdelete-non-virtual-dtor]
delete veh_CAN;
其中程式碼結構大致如下:
class CAN_driver
{
public:
CAN_driver();
~CAN_driver();
}
class CAN_Type1::pubic CAN_driver
{
public:
CAN_Type1()
~CAN_Type1();
}
CAN_driver *veh_CAN = new CAN_Type1();
int main()
{
//application codes.
delete veh_CAN;
return 0;
}
其中CAN_driver是基類,veh_CAN是繼承於CAN_driver的一個類的例項,在定義一個基類的型別的指標用完之後,刪除該指標,則發現出現-Wdelete-non-virtual-dtor型別的警示。
經過查詢相關資料,發現這是一個程式設計習慣錯誤。
基類的解構函式一般需要定義為虛擬函式,則該方法可解,如下所示。
class CAN_driver { public: CAN_driver(); virtual ~CAN_driver(); } class CAN_Type1::pubic CAN_driver { public: CAN_Type1() ~CAN_Type1(); } CAN_driver *veh_CAN = new CAN_Type1(); int main() { //application codes. delete veh_CAN; return 0; }
這是由於在main函式中刪除基類指標時,並不會呼叫繼承類CAN_Type1的解構函式,而基類新增virtual後,則可以。避免了潛在的問題和風險。具體解釋請見參考:https://blog.csdn.net/starlee/article/details/619827