是否使用非虚拟析构函数和基类指针释放了整个对象? [英] Is the whole object freed with a non-virtual destructor and a Base class pointer?

查看:77
本文介绍了是否使用非虚拟析构函数和基类指针释放了整个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果基类没有虚拟析构函数(例如,以避免使用vtable条目)并且派生类仅具有基本属性,则当基类的指针时,它是否释放了new分配的所有内存被删除?我知道不会调用Derived类的析构函数,但是我想知道是否将释放整个对象分配的内存吗?
我还假定对Derived指针调用delete将释放整个内存空间。

If a Base class does not have a virtual destructor (in order to avoid the vtable entry for instance) and the Derived class has only basic attributes, does it free all the memory allocated by new, when the pointer of the Base class is deleted? I know the destructor of the Derived class will not be called but I am wondering if the memory allocated by the whole object will be freed? I assume also that calling delete on a Derived pointer will free the whole memory space.

此外,如果它不释放内存的Derived类部分, ,它如何在相同的情况下如何工作,但在Base类中具有虚拟析构函数,知道要释放多少内存

Also, if it does not free the Derived class part of the memory, how does it work in the same case but with of a virtual destructor in the Base class, to know how much memory to free?

范例:

class Base {
  public:
    int a;
    int b;
   Base() {}
  ~Base() {}
};

class Derived : public Base {
  public:
    int c;
    int d;
    Derived() {}
    ~Derived() {}
};

int main() {
  Base *p = new Derived();
  delete p; // is memory allocated for Derived freed?
  return 0;
}


推荐答案

这是未定义的行为,因此可以发生。引用标准[expr.delete]:

It's undefined behavior, so anything can happen. Quote from the standard [expr.delete]:


在第一个替代方案(删除对象)中,如果对象$ b的静态类型为要删除的$ b与它的
动态类型不同,静态类型应为要删除的对象
的动态类型的
a基类,而
静态类型应为有一个虚拟的
析构函数,或者行为是
未定义。

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

尽管它的工作方式是实现的细节,典型的实现可能会自动覆盖派生类中的析构函数,并在那里实现内存的释放。请注意,必须在基类中定义虚拟析构函数,以便实现可以在虚拟表中保留一个条目。

Although how it works is the detail of implementation, the typical implementation may override automatically the destructor in the derived classes and implement the release of the memory there. Note that you must define the virtual destructor in the base class so the implementation can reserve an entry in the virtual table.

这篇关于是否使用非虚拟析构函数和基类指针释放了整个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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