title: When should I use the new keyword in C++?
body: <p>I've been using C++ for a short while, and I've been wondering about the <code>new</code> keyword. Simply, should I be using it, or not?</p>
  <ol>
  <li>With the <code>new</code> keyword...</li>
  </ol>
  <pre><code>    MyClass* myClass = new MyClass();
      myClass-&gt;MyField = &quot;Hello world!&quot;;
  </code></pre>
  <ol start="2">
  <li>Without the <code>new</code> keyword...</li>
  </ol>
  <pre><code>    MyClass myClass;
      myClass.MyField = &quot;Hello world!&quot;;
  </code></pre>
  <p>From an implementation perspective, they don't seem that different (but I'm sure they are)... However, my primary language is C#, and of course the 1st method is what I'm used to.</p>
  <p>The difficulty seems to be that method 1 is harder to use with the std C++ classes.</p>
  <p>Which method should I use?</p>
  <h3>Update 1:</h3>
  <p>I recently used the <code>new</code> keyword for <em>heap</em> memory (or <em>free store</em>) for a large array which was going out of scope (i.e. being returned from a function). Where before I was using the stack, which caused half of the elements to be corrupt outside of scope, switching to heap usage ensured that the elements were intact. Yay!</p>
  <h3>Update 2:</h3>
  <p>A friend of mine recently told me there's a simple rule for using the <code>new</code> keyword; every time you type <code>new</code>, type <code>delete</code>.</p>
  <pre><code>    Foobar *foobar = new Foobar();
      delete foobar; // TODO: Move this to the right place.
  </code></pre>
  <p>This helps to prevent memory leaks, as you always have to put the delete somewhere (i.e. when you cut and paste it to either a destructor or otherwise).</p>