Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You only need to <code>delete</code> memory you allocate with <code>new</code>.</p> <blockquote> <p>printf would print 5.0, so the variable pointed to by a is not exactly destroyed.</p> </blockquote> <p>You're actually running into undefined behavior. Although the value is still there, the memory was released and can be reused.</p> <p>So the following:</p> <pre><code>struct CoordLocation { float X; float Y; float Z; }; </code></pre> <p>can't create a memory leak if you omit the destructor.</p> <p>Your next snippet:</p> <pre><code>struct CoordLocation { float *X; float *Y; float *Z; }; int main() { CoordLocation *coord = new CoordLocation(); delete coord; return 0; } </code></pre> <p>can potentially create a memory leak, but not as it is. The following will:</p> <pre><code>int main() { CoordLocation *coord = new CoordLocation(); coord-&gt;X = new float(); delete coord; return 0; } </code></pre> <p>Your third example</p> <pre><code>struct CoordLocation { CoordLocation() { *X = new float; *Y = new float; *Z = new float; } ~CoordLocation() { delete X; delete Y; delete Z; } float *X; float *Y; float *Z; }; int main() { CoordLocation *coord = new CoordLocation(); delete coord; return 0; } </code></pre> <p>won't create a memory leak because you free all the memory that you allocate. If you were to omit the destructor or forget to call <code>delete coord;</code>, they you'd have a memory leak.</p> <p>A good rule of thumb: call a <code>delete</code> for every <code>new</code> and a <code>delete[]</code> for every <code>new[]</code> and you're safe.</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