在 C++ 中调用哪个析构函数?
我正在寻找程序中的内存泄漏。
我将范围缩小到一些未调用的析构函数。但是,我不明白为什么:
class CMain : public CList {
public:
CMain();
virtual ~CMain();
...
}
class CList : public CProc {
public:
CList();
virtual ~CList();
...
}
/* some code and a main func here */
CMain *pMain = new CMain();
/* some more code here */
delete pMain;
CMain
被很好地释放,但 ~CList()
从未被调用。 CList
的所有父类也都有虚拟析构函数。
您是否有任何关于为什么从不调用 CList
的析构函数的提示?
I am hunting memory leaks in a program.
I narrowed it down to some destructors not being called. However, I can't figure out why:
class CMain : public CList {
public:
CMain();
virtual ~CMain();
...
}
class CList : public CProc {
public:
CList();
virtual ~CList();
...
}
/* some code and a main func here */
CMain *pMain = new CMain();
/* some more code here */
delete pMain;
CMain
gets deallocated just fine, but ~CList()
is never called. All parent classes of CList
have virtual destructors, too.
Do you have any hints about why the destructor for CList
is never called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你能在 ~CMain 中设置一个断点来看看它去了哪里吗?
Can you set a breakpoint in ~CMain to see where it goes?
也许某处存在切片问题。只是猜测..
什么是对象切片?
不,情况并非如此。
你应该在 ~CMain 中放置一个 try catch 块,嗯,它的成员之一在析构函数中抛出异常?
Maybe there is a slicing problem somewhere. Just guessing..
What is object slicing?
no, this is not that case.
You shuld put a try catch block in ~CMain, hmmm one of its member throw an exception in a destructor?
因为您不会
删除
使用new
分配的对象。;-)
更严重的是,您是否已进入调试 CList 之一的理论范围结束,并进入其销毁过程,会发生什么?
Because you don't
delete
your object allocated withnew
.;-)
More seriously, do you have gone into debugging the theoritical end of scope of one of your CList, and step into its destruction process, what happens?
这听起来像是一个错误的说法。如果
~CMain
被调用,那么~CList
最终也会被调用,因为它是一个基类。检查如何检测析构函数是否被调用。当您说“CMain 被释放”时,您的意思是说您对它发出了
delete
吗?检查在删除 pMain
时,CMain
的类定义是否可见。如果没有定义,编译器可以假设该类没有用户定义的或虚拟析构函数,并且可以省略对它的调用。That sounds like a wrong statement. If
~CMain
is called, then~CList
is eventually called too, because it's a base class. Check how you detect whether or not a destructor is called.When you say "CMain gets deallocated", do you mean to say you issue
delete
on it? Check that at the point you dodelete pMain
, the class definition ofCMain
is visible. In absence of its definition, the compiler is allowed to assume the class doesn't have a user defined or virtual destructor, and can omit calling it.孩子,然后是父母。但在他们之间,孩子的属性就被破坏了。我建议查看 ~CMain 是否运行到最后 - 如果是,并且 ~CList 从未输入,则 CMain 的属性之一有问题。
只是为了演示:
输出:
并退出并返回代码 1。
Child, then parent. But in between them, the attributes of the child are destroyed. I would suggest seeing if ~CMain runs to the end - if it does, and ~CList is never entered, you have a problem with one of the attributes of CMain.
Just to demonstrate:
Outputs:
And exits with return code 1.