虚拟析构函数和内存释放 [英] Virtual destructor and memory deallocation
问题描述
我不太确定我理解虚拟析构函数和在堆上分配空间的概念。让我们看下面的例子:
class Base
{
public:
int a ;
};
类派生:public Base
{
public:
int b;
};
我想象如果我做这样的事情
Base * o = new Derived;
这8个字节(或系统上任何两个整数都需要)那么这样的:
... | a | b | ...
现在,如果我这样做:
;
'delete'如何知道,为了从堆中删除所有内容, ?我想象它必须假设它是类型Base,因此只从堆中删除一个(因为它不能确定b是否属于对象o):
... | b | ...
p>
Base * o = new Derived;
delete o;
真的会引起内存泄漏,我需要一个虚拟析构函数吗?或者删除知道o实际上是Derived类,而不是Base类?如果是,这是如何工作的?
谢谢你们。 :)
你正在做很多假设的实现,这可能
或可能不成立。在 delete
表达式中,动态类型必须是
与静态类型相同,除非静态类型具有虚拟
析构函数。否则,它是未定义的行为。期。这是
真的你所有必须知道—我使用的实现,其中
否则会崩溃,至少在某些情况下;并且我使用
实现,这样做会破坏自由空间竞技场,所以
代码将在某个时候崩溃,在一个完全不相关的块
的代码。 (对于记录,VC ++和g ++都属于第二种情况,在使用已发布代码的通常选项编译时至少为
。)
I'm not quite sure I understand virtual destructors and the concept of allocating space on the heap right. Let's look at the following example:
class Base
{
public:
int a;
};
class Derived : public Base
{
public:
int b;
};
I imagine that if I do something like this
Base *o = new Derived;
that 8 Bytes (or whatever two integers need on the system) are allocated on the heap, which looks then something like this: ... | a | b | ...
Now if I do this:
delete o;
How does 'delete' know, which type o is in reality in order to remove everything from the heap? I'd imagine that it has to assume that it is of type Base and therefore only deletes a from the heap (since it can't be sure whether b belongs to the object o): ... | b | ...
b would then remain on the heap and be unaccessible.
Does the following:
Base *o = new Derived;
delete o;
truly provoke memory leaks and do I need a virtual destructor here? Or does delete know that o is actually of the Derived class, not of the Base class? And if so, how does that work?
Thanks guys. :)
You're making a lot of assumptions about the implementation, which may
or may not hold. In a delete
expression, the dynamic type must be the
same as the static type, unless the static type has a virtual
destructor. Otherwise, it is undefined behavior. Period. That's
really all you have to know—I've used with implementations where
it would crash otherwise, at least in certain cases; and I've used
implementations where doing this would corrupt the free space arena, so
that the code would crash sometime later, in a totally unrelated piece
of code. (For the record, VC++ and g++ both fall in the second case, at
least when compiled with the usual options for released code.)
这篇关于虚拟析构函数和内存释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!