【发布时间】:2013-02-22 11:20:37
【问题描述】:
在下面的代码中,当ptr被删除时,Base的析构函数被调用,而不是Derived的析构函数(因为Base的析构函数不是虚拟的)。
class Base
{
int b;
};
class Derived : public Base
{
int d;
};
int main(void)
{
Base * ptr = new Derived();
delete ptr;
return 0;
}
Valgrind 报告说该程序不包含内存泄漏,我猜这是真的,因为在这种特殊情况下所有新数据都被删除了。 我的问题是 - 鉴于 Derived 的(默认)析构函数未被调用,d 的内存何时以及如何被释放或回收?
【问题讨论】:
-
我相信,由于
delete ptr,内存被回收了,只是没有调用析构函数,这可能是一个潜在未定义的行为。 -
没有潜力。这是未定义的行为。 (§5.3.5/3)
-
你的 valgrind 调用说“没有内存泄漏”,我的
MemoryLogger说allocated 8 bytes at 0x3b2380; deallocated 4 bytes at 0x3b2380; Error: 4 bytes still allocated!。 UB。可能这也可以说是Have a nice day sir。 -
@iammilind:这是潜在的泄漏,因为
Derived可能负责一些因此不会被释放的更多资源。
标签: c++