虚拟析构函数在多态性中的基类丢失= Ressource泄漏? [英] Virtual destructor missing for base class in polymorphism = Ressource leak?

查看:103
本文介绍了虚拟析构函数在多态性中的基类丢失= Ressource泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,如果您打算以多态方式使用基类,则需要将基类的析构函数指定为virtual,否则您的程序中可能会有一个ressource泄露,因为只有基类析构函数被调用,而不是派生对象析构函数。



我们还知道构造函数/析构函数是纯初始化/未初始化结构,操作符new / operator delete处理内存的分配/ >

在这种情况下,为什么缺少析构函数调用导致泄漏,在我的C ++类只包含原始数据成员的情况下?
更准确的说,操作符delete不能分配内存,这是什么造成了资源泄露?



编辑:添加一个例子,澄清我的问题。在下面的情况下,派生析构函数不会被调用。这是否意味着derivedInt的内存从未获得未分配?在这种情况下,是因为析构函数不能被调用,还是因为操作符delete不能为int分配内存。

  class Base 
{
int baseInt;
public:
Base(){};
〜Base(){};
};

类派生:public Base
{
int derivedInt;
public:
Derived(){};
〜Derived(){};
};

int main(int argc,const char * argv []){

Base * pb = new Derived();
delete pb;

return 0;
}


解决方案

通过指针删除对象base调用未定义的行为,除非基类中的析构函数是virtual。 来源



此意味着任何可能发生的事情 - 包括内存泄漏。


We know that it is needed to specify the destructor of a base class as virtual if you intend to use it polymorphically, otherwise you might have a ressource leak in your program, since only the base class destructor will be called and not the derived object destructor.

We also know that constructors / destructors are purely initialization / uninitialization constructs, and operator new / operator delete handle the allocation / unallocation of memory.

In that case, why exactly does the lack of destructor-calling incur a leak, in the case where my C++ class contains only primitive data members? Would it be more accurate to say that the operator delete cannot unallocate the memory, and that is what creates a resource leak?

EDIT: Adding an example, to clarify my question. In the following case, the derived destructor never gets called. Does it mean that the memory for derivedInt never gets unallocated? In that case, is it because the destructor cannot be called, or because the operator delete cannot unallocate the memory for the int?

class Base
{
    int baseInt;
public:
    Base(){};
    ~Base(){};
};

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

int main(int argc, const char * argv[]) {

    Base *pb = new Derived();
    delete pb;

    return 0;
}

解决方案

Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual. Source

This means anything can happen - including a memory leak.

这篇关于虚拟析构函数在多态性中的基类丢失= Ressource泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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