Thread: Interesting question of "delete this"..

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    Interesting question of "delete this"..

    Code:
    class Test2{
    public:
    	~Test2(){
    		cout<<"destructor in"<<endl;
    		delete this;
    		cout<<"destructor out"<<endl;
    	}
    };
    
    Test2 ts;
    I thought the program should loop forever, however the result is just about 10 lines of "destructor in". I was using VS 2005. What's happening?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I guess we are talking about undefined behaviour. So it is rather pointless to discuss why it prints it exactly 10 times (it goes into an infinite loop with mingw).

    Also see this FAQ about deleting the same pointer more than once.

    And this FAQ about "delete this"
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by meili100 View Post
    I thought the program should loop forever, however the result is just about 10 lines of "destructor in". I was using VS 2005. What's happening?
    It didn't crash at the end? Funny.

    A recursive destructor -- can't say I've seen that one before! It wouldn't ever infinite loop even in theory, because it's not tail-recursive, so it eats stack space until you run out of memory.

    Or, in your case, it terminates far before that point. Interesting, but ultimately pointless to examine it further

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  2. Question type program for beginners
    By Kirdra in forum C++ Programming
    Replies: 7
    Last Post: 09-15-2002, 05:10 AM
  3. Hi this programm is interesting and tough..
    By datainjector in forum C Programming
    Replies: 5
    Last Post: 06-27-2002, 08:02 PM
  4. Iterator Question - interesting
    By ginoitalo in forum C++ Programming
    Replies: 4
    Last Post: 02-24-2002, 07:04 PM
  5. interesting question...
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-13-2002, 10:13 PM