Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you write</p> <pre><code>fool-&gt;~Fool(); </code></pre> <p>You end the object's lifetime, which invokes the destructor and reclaims the inner <code>array</code> array. The memory holding the object is not freed, however, which means that if you want to bring the object back to life using placement new:</p> <pre><code>new (fool) Fool; </code></pre> <p>you can do so. </p> <p>According to the spec, reading or writing the values of the fields of <code>fool</code> after you explicitly invoke the destructor results in undefined behavior because the object's lifetime has ended, but the memory holding the object should still be allocated and you will need to free it by invoking <code>operator delete</code>:</p> <pre><code>fool-&gt;~Fool(); operator delete(fool); </code></pre> <p>The reason to use <code>operator delete</code> instead of just writing</p> <pre><code>delete fool; </code></pre> <p>is that the latter has undefined behavior, because <code>fool</code>'s lifetime has already ended. Using the raw deallocation routine <code>operator delete</code> ensures that the memory is reclaimed without trying to do anything to end the object's lifetime.</p> <p>Of course, if the memory for the object didn't come from <code>new</code> (perhaps it's stack-allocated, or perhaps you're using a custom allocator), then you shouldn't use <code>operator delete</code> to free it. If you did, you'd end up with undefined behavior (again!). This seems to be a recurring theme in this question. :-)</p> <p>Hope this helps!</p>
 

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