I was writing a class and came up to something that I needed to do. I needed
the class to delete itself inside a function. I realized that this is
illegal, and thought of a way around it. Later, out of curiosity, I tried
this.
class A
{
public:
int var;
void Delete();
};
int main()
{
A a;
a.Delete();
return (0);
}
void A::Delete()
{
delete this;
}
It compiled correctly. At runtime, however, I got an assertation failure (I
believe that's a compiler specific feature) and then hit a hard-coded
breakpoint. That was, AFAIK, at delete this. When setting it in non-debug
mode (optimized and takes out all assertation failures), it just hits the
breakpoint. If I were to run the program outside of the debugger, nothing
happens (just a blank screen). What is supposed to happen? I doubt this is
standardized but if it is what paragraph is it in and what is the compiler
supposed to do. Don't you think there should be some kind of warning the
compiler generates for this?
I realize that the this pointer is only a A * const so technically its
legally deleted, but it just doesn't make sense to be deleting this. Why
aren't compilers smarter than they are?
No warnings at highest warning level.
--
MiniDisc_2k2