使用基类指针删除派生类时发生内存泄漏 [英] memory leak when deleting derived class with base-class pointer

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

问题描述

我的内存泄漏有问题.我有一个基类的指针.从中,我使用new分配不同的派生类.然后,当我尝试使用引用delete这些类(未强制转换)时,出现内存泄漏.我研究了这个问题,发现我应该在基类中添加一个虚拟析构函数,但是我尝试了这一点,但仍然存在内存泄漏.也就是说,根据我的任务管理器,每次使用基类指针分配和删除派生类时,内存使用量将继续上升.我尝试使其成为抽象析构函数,并将析构函数添加到派生类,但出现未定义的引用错误.我还尝试将指针类型转换为delete的派生类指针,但是显然这会使程序崩溃.

I have an issue with a memory leak. I have a base-class pointer. From it, I use new to allocate different derived classes. Then, when I try to delete those classes with the reference (not typecasted), I get a memory leak. I researched the problem and found that I should add a virtual destructor to the base-class, but I tried this and I still have a memory leak; that is, according to my task-manager, the memory usage continues to rise with each allocation and deletion of the derived class using the base-class pointer. I tried making it an abstract destructor and added destructors to the derived classes, but I got an undefined reference error. I also tried typecasting the pointer as a derived-class pointer for the delete, but apparently this crashes the program.

有人知道我应该做什么吗?

Does anyone have any idea what I should do?

示例代码:

class A {
public:
  A();
  ~A() {};
  virtual ~A();      /*or*/
  virtual ~A()=0;    /*or*/
                     /*or nothing?*/
}

class B: private A {
public:
  B();
  ~B() {};           /*this?*/
                     /*or nothing?*/
}

推荐答案

使用virtual ~A();

如果允许使用virtual ~A()=0,我会感到惊讶.

I'd be surprised if virtual ~A()=0 is allowed.

使用以下代码:

A* base = new B();
delete base;

B的析构函数然后是A会被调用.

the destructor for B then A will be called.

如果您确实还在泄漏内存,那么其他地方还会泄漏.

If you're really still leaking memory, then you have another leak elsewhere.

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

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