正向声明和析构函数之间的关系 [英] The relation between Forward declaration and destructors
问题描述
我有以下代码:
#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();
}
我运行程序,并且什么都不打印。
I ran the program, and it printed nothing.
为什么?
在main中,我创建了 new CFoward
code> func 我删除它并将其称为析构函数。
in main, I created new CFoward
, and in func
I deleted it and called it destructor.
似乎析构函数没有被调用。为什么?
It seems that the destructor have not been called. Why? Is that related anyhow to the forward decleration?
推荐答案
事实上,你的前向声明引入了一个不完整的类型,并且不能在删除表达式中使用:
Indeed, your forward declaration introduces an incomplete type that is later defined with a non-trivial destructor, and that can't be used in a delete expression:
从n3337第5.3.5 / 5节:
From n3337, paragraph 5.3.5/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.
这篇关于正向声明和析构函数之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!