Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Okay, we understood that behavior is not defined. But let's do small journey into what really happends. I use VS 2008. </p> <p>Here is my code:</p> <pre><code>class Test { int i; public: Test() : i(3) { } ~Test() { if (!i) return; printf("%d", i); i--; Test::~Test(); } }; int _tmain(int argc, _TCHAR* argv[]) { delete new Test(); return 0; } </code></pre> <p>Let's run it and set a breakpoint inside destructor and let the miracle of recursion happen. </p> <p>Here is stack trace:</p> <p><a href="http://img638.imageshack.us/img638/8508/dest.png" rel="nofollow noreferrer">alt text http://img638.imageshack.us/img638/8508/dest.png</a></p> <p>What is that <code>scalar deleting destructor</code>? It is something that compiler inserts between delete and our actual code. Destructor itself is just a method, there is nothing special about it. It doesn't really release the memory. It is released somewhere inside that <code>scalar deleting destructor</code>. </p> <p>Let's go to <code>scalar deleting destructor</code> and take a look at the disassembly:</p> <pre><code>01341580 mov dword ptr [ebp-8],ecx 01341583 mov ecx,dword ptr [this] 01341586 call Test::~Test (134105Fh) 0134158B mov eax,dword ptr [ebp+8] 0134158E and eax,1 01341591 je Test::`scalar deleting destructor'+3Fh (134159Fh) 01341593 mov eax,dword ptr [this] 01341596 push eax 01341597 call operator delete (1341096h) 0134159C add esp,4 </code></pre> <p>while doing our recursion we are stuck at address <code>01341586</code>, and memory is actually released only at address <code>01341597</code>. </p> <p>Conclusion: In VS 2008, since destructor is just a method and all memory release code are injected into middle function (<code>scalar deleting destructor</code>) it is safe to call destructor recursively. But still it is not good idea, IMO.</p> <p><strong>Edit</strong>: Ok, ok. The only idea of this answer was to take a look at what is going on when you call destructor recursively. But don't do it, it is not safe generally.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload