简体   繁体   English

为什么非虚拟析构函数没有 memory 泄漏

[英]Why is there no memory leak with non-virtual destructor

I was told that there is no memory leak of B->b in the following code:我被告知在以下代码中没有B->b的 memory 泄漏:

    struct A {}; // no virtual destructor
    struct B : public A {
    int b;
    }

    int main() {
        A* a = new B {};
        delete a;
    }

If it's true, could you explain why?如果是真的,你能解释一下为什么吗?

Because that is how undefined behaviour works.因为这就是未定义行为的工作方式。 Memory isn't guaranteed to leak. Memory 不保证泄漏。 But neither is it guaranteed to not leak.但也不能保证不泄漏。 Any behaviour is possible as far as the language is concerned.就语言而言,任何行为都是可能的。

why this is Undefined Behaviour为什么这是未定义的行为

Because a non-virtual destructor is called through a pointer whose dynamic type is of another (derived) type.因为非虚拟析构函数是通过动态类型是另一个(派生)类型的指针调用的。

whether anything concretely can be said about the lifetime of the B::b是否可以具体说明 B::b 的生命周期

Well, it is a member of B , so it has the same lifetime as any B object.好吧,它是B的成员,因此它与任何B object 具有相同的生命周期。 As for the lifetime of the dynamic B object, we cannot really say much due to the UB.至于动态B object 的寿命,由于 UB,我们不能说太多。

There's nothing in your structure to leak.你的结构中没有任何东西可以泄漏。

Your destructor doesn't delete the object -- it deletes any memory the object itself creates.您的析构函数不会删除 object - 它会删除 object 本身创建的任何 memory。 For instance, if your "int b" were instead something that itself required destruction, you might have a different problem.例如,如果您的“int b”是本身需要销毁的东西,那么您可能会遇到不同的问题。

But b itself doesn't require destruction.但是 b 本身不需要破坏。

You could test this after a fashion by doing almost the same, but making a second class that has a constructor and destructor.您可以通过几乎相同的方式进行测试,但制作第二个具有构造函数和析构函数的 class。 Add cout statements in each, and instead of "int b" have first a (non-pointer) instance to your new structure and then a pointer version (that you do a new Foo on), and see what happens.在每个中添加 cout 语句,而不是“int b”,首先有一个(非指针)实例到你的新结构,然后是一个指针版本(你在上面做一个新的 Foo),看看会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM