Re: Destructor not called with forward declaration instead of include
On 22 Apr, 04:43, internetpet <internet...@hotmail.com> wrote:
Say you have these files:
BigClazz.h
class Clazz; // Note the forward declaration only , no include
"Clazz.h"
class BigClazz
{
public:
BigClazz();
~BigClazz();
Clazz* pclazz;
};
BigClazz.cpp
#include "BigClazz.h"
BigClazz::BigClazz(){}
BigClazz::~BigClazz()
{
delete pclazz; // Here the destructor of of the Clazz object
will not be called
}
Clazz.h
class Clazz
{
public:
Clazz();
~Clazz();
};
Clazz.cpp
#include "Clazz.h"
Clazz::Clazz(){};
Clazz::~Clazz(){};
main.cpp
int main(int argc, char *argv[])
{
BigClazz* pVM = new BigClazz();
pVM->pclazz = new Clazz();
delete pVM;
}
If you run this you'll see that the Clazz destructor will not be
called when BigClazz does "delete pclazz;" in it's own destructor. But
if you replace the forward declaration in BigClazz (class Clazz;) with
an include
(#include "Clazz.h") then it works.
Any idea why?
Yes. According to [expr.delete]/5 in the standard (with my comments in
parens):
If the object being deleted has incomplete class type (in this case,
forward declared) at the point of deletion and the complete class has
a non-trivial destructor (you declared your own dtor, so it's non-
trivial) or a deallocation function, the behavior is undefined (which
usually means not calling the destructor in this case).
To fix this, simply #include "Clazz.h" in BigClazz.cpp, so that the
type is complete at the point of deletion.
--
DP
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]