I got asked this question as an interview question at the Engineering Expo at U of I and thought it was a really good interview question because it's non-trivial but a reasonable answer can be given if you just think about it for a few minutes. The humorous thing was that once the interviewer and I started talking about it, it turned out he didn't really know the answer himself - it was more intended to see how an interviewer would respond to an odd question. So what would happen?

Caveat: this is probably an incomplete answer so please feel free to correct me or add things I'm missing.

The first step is to ask "What does delete p do?" It's basically a two step operation:

  1. Call p's destructor (your code)
  2. Free the allocated memory for p (C++ runtime)

delete this works in exactly the same way. The first thing that happens is the destructor for your class is called - so there goes all your heap allocated memory (you don't have any memory leaks, right?). No big deal, this just means that after calling delete this you can't use any of your heap allocated memory or anything else that you clean up in your destructor.

Next, the C++ runtime frees the memory it allocated for your class. This means bye-bye for your member variables and function pointers. Interestingly, they may continue to work for a little while since their memory might not be reclaimed right away. I remember reading on Raymond Chen's blog that the Windows folks had to tweak the Windows memory manager to delay reclaiming memory for certain programs because those programs relied on just this behavior. Remember that old saying "DOS ain't done until Lotus won't run"? Yeah, it's bull. In any case, this means that you can't call any member functions or access any member variables after you call delete this.

OK, so where does that leave us? Well, delete this hasn't messed with our instruction pointer (except to make the proper function calls), so your code will happily continue to run. As long as you play it safe and pretend that your class instance basically doesn't exist any more you can execute as much code as you want. This might even be handy because you now have the ability to safely commit class suicide. However, just like human suicide, it would probably be nice to leave a note for your caller in the form of a return value to let them know what happened.

July 1, 2010 at 19:40:05
What is <b><a href=http://www.replica-watch-sale.com/>Breitling</a></b>? Do you know <b><a href=http://www.replica-watch-sale.com/>Breitling Watches</a></b>? Buy these <b><a href=http://www.replica-watch-sale.com/>Breitling Watches sale</a></b> on line.More <b><a href=http://www.replica-watch-sale.com/>cheap Breitling Watches</a></b> for sale! %u5CA9%u59D0%u6D4B%u8BD5%uFF01%u5982%u6709%u96F7%u540C%uFF0C%u7EAF%u5C5E%u5DE7%u5408%uFF01

Add a Comment

June 7, 2009 at 10:26:42
Hide Comments (1)