What is this supposed to do?

M

MiniDisc_2k2

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.
 
A

Alexander Terekhov

MiniDisc_2k2 wrote:
[...]
Why aren't compilers smarter than they are?

Because

int main() {
A & a = *new A;
a.Delete();
}

is just fine.

regards,
alexander.
 
S

Stephen Howe

Why aren't compilers smarter than they are?

Because they cannot always spot programmers shooting themselves in the foot.

Stephen Howe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top