delete-non-virtual-dtor 问题解决办法
程序员文章站
2022-05-08 22:38:26
...
编译过程中出现如下警告:
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