Re: Explain class method invocation after delete
On May 18, 3:25 pm, UConnFan <mruvi...@optonline.net> wrote:
If you have this:
Class Test {public: void foo() { cout << "foo()" << endl; }
Test *ptr = new Test();
delete ptr;
ptr->foo(); /// invoke method on deleted object
1. Why does this ptr->foo() still work?
Undefined behavior doesn't mean that the program necessarily crashes.
It just means that you can't rely on the behavior. It might break on a
different compiler, different machine, or just different phase of the
moon.
2. How are class non-static methods implemented ?
Depends on the compiler, really, but all that I know implement non-
virtual member functions like normal functions, transforming the
object to another argument.
So to answer why your program still "works", there are two reasons.
First, you don't use the object at all in your function, so the
invalid this pointer that is passed is never accessed. Second,
deleting an object doesn't usually make the memory disappear, it just
marks it as reusable in the memory allocator's data structures. So
accessing that memory still seems to work. But the allocator might
give the memory to someone else, and then you have a really, really
nasty bug.
Sebastian
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]