【发布时间】:2013-07-28 18:40:25
【问题描述】:
我有以下代码:
#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中我删除了它并称之为析构函数。
似乎没有调用析构函数。为什么?这与前向减速有关吗?
【问题讨论】:
-
g++实际上会告诉你编译这段代码时发生了什么。 -
至少提高编译器的警告级别。这应该始终发出“删除指向不完整类型的指针”诊断信息。
-
GCC 很有帮助:
warning: possible problem detected in invocation of delete operator: [enabled by default] ‘frw’ has incomplete type [enabled by default] forward declaration of ‘class CForward’ [enabled by default] note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.