Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top