c++ - 前向声明与析构函数的关系

标签 c++ forward-declaration

我有以下代码:

#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/

相关文章:

C++ 对象的前向声明

c++ - 为什么我不能通过别名来定义前向声明的类?

c++ - C++ 中带有对象名称的 typedef 结构的前向声明

c++ - 返回原始类型和结构的本地对象

c++ - 枚举 Windows 中可用的键盘布局

c++ - 为什么我可以在没有前向声明的情况下调用函数模板?

c - 如何转发声明一个以函数指针作为参数的函数?

c++ - OpenCV C++/Obj-C : Detecting a sheet of paper/Square Detection

c++ - 为什么我的 libmpg123 构建不支持 float ?我如何启用它?

c++ - 类型比较