非虚拟微小析构函数+继承 [英] Non-virtual trivial destructor + Inheritance

查看:268
本文介绍了非虚拟微小析构函数+继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个类及其所有子类只需要默认的析构函数来释放它们的资源,如果存储在一个精确类型的变量(或指向精确类型的指针),一个子类泄漏内存类指针,然后由指针删除



示例:



 #include< memory> 

class A {
};

class B:public A {
public:
B():pInt(new int){}
auto_ptr< int>品脱; //这是什么可能泄漏...可能更多的会,虽然
};

void will_this_leak(){
A * pA = new B();
删除pA;
}


解决方案

Leak memory?



您发布的代码会产生未定义的行为。在这种情况下可能发生的任何事情:内存泄漏,格式化硬盘,程序崩溃等。



我知道有一个流行的城市传说,执行多态破坏没有虚拟析构函数可能泄漏内存。我不知道是谁发明了废话,为什么他们决定使用泄漏记忆作为可能发生的主要场景。在现实中,这种情况下的行为与泄漏记忆完全无关。



从实际的角度来看,在你的特定情况下,很明显你的<$ c $的析构函数没有真正的机会c> auto_ptr 来调用,因此 auto_ptr 拥有的内存肯定会被泄露。但是,这也是这段代码中最小的问题。


Given that a class and all its subclasses need no more than the default destructor to release their resources if stored in a variable of the exact type (or pointer to the exact type), can a subclass leak memory if referenced by a base class pointer and then deleted by that pointer?

Example:

#include <memory>

class A {
};

class B : public A {
public:
    B () : pInt(new int) {}
    auto_ptr<int> pInt; // this is what might leak... possibly more will though
};

void will_this_leak () {
    A *pA = new B();
    delete pA;
}

解决方案

"Leak memory"? Why are you talking about leaking memory specifically?

The code you posted produces undefined behavior. Anything can happen in this case: memory leaked, hard drive formatted, program crashed, etc.

P.S. I know that there's a popular urban legend out there that performing polymorphic destruction without a virtual destructor "might leak memory". I don't know who invented that nonsense and why they decided to use "leaking memory" as the primary scenario for what might happen. In reality the behavior in this case has absolutely nothing to do with "leaking memory". The behavior is simply undefined.

From the practical point of view, in your particular case it is rather obvious that there's no real chance for the destructor of your auto_ptr to get called, so the memory owned by that auto_ptr will certainly be leaked. But again, this is the least of this code's problems.

这篇关于非虚拟微小析构函数+继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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