我有以下代码:
#include <iostream>
using namespace std;
class CForward;
void func(CForward* frw) { delete frw; }
class CForward
{
public:
~CForward() { cout << "Forward" << endl; }
};
int main()
{
func(new CForward);
cin.get();
}
我运行了这个程序,它什么也没打印出来。
为什么?
在 main 中,我创建了 new CFoward
,在 func
中我删除了它并称之为析构函数。
似乎没有调用析构函数。为什么?这与前向减速有关吗?
最佳答案
确实,您的前向声明引入了一个不完整的类型,该类型后来使用非平凡的析构函数定义,并且不能在删除表达式中使用:
来自 n3337,第 5.3.5/5 段:
5 If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
关于c++ - 前向声明与析构函数的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911539/