Re: Explain class method invocation after delete
Am 18.05.2011 23:25, schrieb UConnFan:
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?
There is no universally correct answer to that question, because the
behaviour of the code is undefined.
2. How are class non-static methods implemented ?
Differently ;-) but some implementations realize non-virtual member
functions as normal function with one additional (hidden) function
parameter (usually the first one) that has the type of a pointer to the
class type (Test* in your example). In such implementations, this
argument is not actually dereferenced in the third line and so the code
might "work" (which is a valid manifestation of undefined behaviour).
But several implementations may simply abort, especially if some pointer
values can raise special hardware "exceptions".
To emphasize this: You should not rely on this behaviour!
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]