Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li>Do not make assumptions about the size of data-types, they are implementation dependent.</li> <li><code>MyClass *t1</code> defines an uninitialized pointer. Dereferencing it invokes <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="noreferrer">undefined behavior</a>.</li> <li><code>t1 = (MyClass *)new MyClass;</code> allocates memory on the heap and creates a new object. If this memory does not get deallocated using <code>delete</code>, there will be a memory leak. Also, you do not need the cast there, <code>t1 = new MyClass();</code> suffices.</li> </ol> <p><strong>Edit:</strong> About allocation. </p> <pre><code>MyClass *t1 = NULL; </code></pre> <p>declares a pointer to a <code>MyClass</code>-object, but it does not create the object. This pointer is initialized to point to <code>0</code>. Now when you do</p> <pre><code>t1 = new MyClass(); </code></pre> <p>the operator <code>new</code> creates a new instance of <code>MyClass</code> and assigns the address of that object to <code>t1</code>. You can now work with that object through <code>t1</code>:</p> <pre><code>t1-&gt;doStuff(); </code></pre> <p>You can even create more pointers that point to the same object:</p> <pre><code>MyClass *t2 = t1; </code></pre> <p>Now <code>t2</code> and <code>t1</code> point to the same object. When you are done with the object, just do:</p> <pre><code>delete t1; </code></pre> <p>(<code>delete t2</code> would have the same effect). Now the object is destroyed, but the pointers still point to the same address (which is not safe anymore). Doing</p> <pre><code>t2-&gt;doStuff(); </code></pre> <p>after the <code>delete</code> invokes undefined behavior. If we go back to before the delete, consider this:</p> <pre><code>t1 = NULL; t2 = NULL; </code></pre> <p>Now we do not have the address of the object we created anymore, so we cannot call <code>delete</code> on it. This creates a memory leak. This hopefully gives you some understanding of what is going on. Now forget all this and read about <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a>.</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