虚拟析构函数:是不是动态分配内存时需要的? [英] Virtual destructor: is it required when not dynamically allocated memory?

查看:108
本文介绍了虚拟析构函数:是不是动态分配内存时需要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的类不动态分配任何内存,我们需要一个虚拟析构函数吗?

Do we need a virtual destructor if my classes do not allocate any memory dynamically ?

例如

class A
{
      private: 
      int a;
      int b;

      public:
      A();
      ~A();
};

class B: public A
{     
      private:
      int c;
      int d;

      public:
      B();
      ~B();
};

在这种情况下,我们需要将A的析构函数标记为虚拟的吗?

In this case do we need to mark A's destructor as virtual ?

推荐答案

问题不在于你的类是否动态分配内存。这是如果类的用户通过A指针分配一个B对象,然后删除它:

The issue is not whether your classes allocate memory dynamically. It is if a user of the classes allocates a B object via an A pointer and then deletes it:

A * a = new B;
delete a;

在这种情况下,如果没有A的虚拟析构函数,C ++标准说你的程序展示未定义的行为。这不是一件好事。

In this case, if there is no virtual destructor for A, the C++ Standard says that your program exhibits undefined behaviour. This is not a good thing.

此行为在标准的5.3.5 / 3节中指定(这里指 delete ):

This behaviour is specified in section 5.3.5/3 of the Standard (here referring to delete):


如果操作数的静态类型是
不同于其动态类型,
静态类型应该是
的基类,操作数的动态类型和
静态类型应该有一个虚拟的
析构函数或行为是
未定义。

if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

这篇关于虚拟析构函数:是不是动态分配内存时需要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆