没有虚拟析构函数可能存在内存泄漏?

Possible memory leak without a virtual destructor?(没有虚拟析构函数可能存在内存泄漏?)

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

问题描述

#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[] 表达式):

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.

静态类型(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.

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

本文标题为:没有虚拟析构函数可能存在内存泄漏?