Thanks Victor. I understand what you said and knew. Let me put more
detected.
mc wrote:
This may be obvious but I can't find anything one way or another. We
have a class which is always allocated using new, e.g. Foo* foo = new
Foo() so we came up with the idea of releasing the memory from the
destructor as follows:
Foo::Foo()
{
// Initialize stuff
m_This = this; // m_This is a "void*"
}
Foo::~Foo()
{
// Release all resources
// and finally the memory
delete m_This;
}
It's been working fine so far (both Windows and Linux) but we're
wondering about it being either the worse thing to do..... Any thoughts.
That is a VERY BAD IDEA. Basically, the only correct way to invoke the
destructor of an object that was created dynamically is to use 'delete'
with the expression evaluating to the pointer to that object. In most
cases if you have
Foo* foo = new Foo();
somewhere, then somewhere else you have
delete foo;
That will invoke the destructor and *then* deallocate the memory. Now, if
you duplicate the pointer somewhere (in the object itself, or in some
other place), and then use 'delete' with that pointer, you will be
*deleting* the object twice. I am not sure what 'delete (void*)ptr' does
(or does not) compared to 'delete ptr'. Most likely it can't call the
destructor since the type is unknown. But it will, and I am certain of
it, deallocate the memory.
So, if you do use 'delete' with your 'foo', you're deallocating the memory
twice, which is undefined behaviour. If you don't use 'delete foo', then
how do you get the destructor to be called? DO you call it explicitly
(foo->~Foo();)? Then it's rather nonsensical, you should instead use the
normal idiomatic way and let the system perform all the necessary clean-up
for you.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask