将使用删除与基类指针导致内存泄漏? [英] Will using delete with a base class pointer cause a memory leak?

查看:104
本文介绍了将使用删除与基类指针导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个类只有原始数据类型,没有自定义析构函数/释放器。
C ++规范是否保证它将按正确的大小释放?

  struct A {int foo; }; 
struct B:public A {int bar [100000]; };
A * a =(A *)new B;
delete a;

我想知道我需要写一个空的虚拟 dtor?



我试过g ++和vc ++ 2008,他们不会导致泄漏。但是我想知道C ++标准是什么。

解决方案

除非基类析构函数是虚函数,否则是未定义的行为。参见5.3.5 / 4:


如果操作数[的删除操作符]的静态类型与其动态类型不同,静态类型应该是操作数动态类型的基类,静态类型应该有一个虚拟析构函数或行为是未定义的。



Given two classes have only primitive data type and no custom destructor/deallocator. Does C++ spec guarantee it will deallocate with correct size?

struct A { int foo; };
struct B: public A { int bar[100000]; };
A *a = (A*)new B;
delete a;

I want to know do I need to write an empty virtual dtor?

I have tried g++ and vc++2008 and they won't cause a leak. But I would like to know what is correct in C++ standard.

解决方案

Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4:

If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.

这篇关于将使用删除与基类指针导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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