Re: Deleting from destructor
You did it again. Please do not top-post. It is frowned upon around these
parts.
mc wrote:
Why is there a need for the original's destructor to be called? After all,
the original is copied verbatim and consequently the destructor is called
once as expected.
[snip]
I am not sure, I understand your code. You have:
Foo::Foo() {
// Initialize stuff
m_This = this; // m_This is a "void*"
}
Foo::~Foo() {
// Release all resources
// and finally the memory
delete m_This;
}
const FOO& MCU::foo() {
return (*new Foo());
}
and then
FOO foo = mcu.foo(); // creates a copy
Now the destructor of the foo object will be called. This destructor, in
turn, is going to invoke
delete m_This;
which will call the destructor for the original. Here is what I do not
understand:
a) Why is m_This a void*? It appears that in this case
delete m_This;
will _not_ invoke the destructor of the original.
b) Why are you not running into an infinite loop? After all, the destructor
of the original, once invoked, has to execute
delete m_This;
too.
c) Could it be that (a) and (b) are related, i.e., do you run into an
infinite loop if m_This had type foo*? If that is the case, then with the
delete m_This;
statement in the destructor of the copy foo, you are likely invoking
undefined behavior because of a type mismatch of the actual object and what
you are telling the compiler [5.3.5/3].
Best
Kai-Uwe Bux