13

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?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Billie
  • 8,938
  • 12
  • 37
  • 67
  • `g++` actually tells you what's happening when you compile this code. – fuenfundachtzig Jul 28 '13 at 18:49
  • 2
    At least bump up the warning level on your compiler. This should always emit a "deletion of pointer to incomplete type" diagnostic. – Hans Passant Jul 28 '13 at 18:49
  • GCC is quite helpful: `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`. – juanchopanza Jul 28 '13 at 18:53

2 Answers2

12

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.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • 3
    @user1798362: If you defined your class destructor(rather than just using the compiler generated one), it is non-trivial. Recursively, if your class has any members with non-trivial destructors, your class has a non-trivial destructor. All other destructors are trivial (they don't actually do anything). – Benjamin Lindley Jul 28 '13 at 18:50
1

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.

Joyas
  • 433
  • 3
  • 6