没有虚拟析构函数可能的内存泄漏? [英] Possible memory leak without a virtual destructor?

查看:169
本文介绍了没有虚拟析构函数可能的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;
class base
{
   int a;
 public: 
   base() {a =0;}
 };
 class derv :public base
 {
   int b;
  public:
   derv() {b =1;}
 };
 int main()
 {
    base *pb = new derv();
    delete pb;
 }



我在derv类中没有虚拟析构函数,基础部分derv对象?

I don't have a virtual destructor in derv class, does it delete only base part of derv object??

因为

推荐答案

base 没有虚拟析构函数,您的代码显示未定义的行为。任何事情都可能发生。它可能看起来像你期望的工作。它可能泄漏内存。它可能会导致您的程序崩溃。它可能会格式化您的硬盘驱动器。

Because base does not have a virtual destructor, your code exhibits undefined behavior. Anything might happen. It might appear to work as you expect. It might leak memory. It might cause your program to crash. It might format your hard drive.

请求引用。 C ++ 11§5.3.5/ 3声明,对于标量 delete 表达式(即不是 delete [] expression):

A citation was requested. C++11 §5.3.5/3 states that, for a scalar delete expression (i.e., not a delete[] expression):


如果要删除的对象的静态类型与其动态类型不同,则静态类型应为

if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.





$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

静态类型( base )与动态类型( derv )不同,没有虚拟析构函数,所以行为是未定义的。

The static type (base) is different from the dynamic type (derv) and the static type does not have a virtual destructor, so the behavior is undefined.

这篇关于没有虚拟析构函数可能的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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