Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The relation between Forward declaration and destructors

I have the following code:

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

Why?

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?

like image 227
Billie Avatar asked Jul 28 '13 18:07

Billie


2 Answers

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:

From n3337, paragraph 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.

like image 147
jrok Avatar answered Oct 07 '22 06:10

jrok


Yes. In fact in the function func, the compiler doesn't know the complete type of cForward. So the desctructor is neved called.

If you put the function after the class, it will work fine.

like image 35
Joyas Avatar answered Oct 07 '22 07:10

Joyas