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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With