title: Dynamically allocating an array of objects
body: <p>I have a class that contains a dynamically allocated array, say</p>
  
  <pre><code>class A
  {
      int* myArray;
      A()
      {
          myArray = 0;
      }
      A(int size)
      {
          myArray = new int[size];
      }
      ~A()
      {
          // Note that as per MikeB's helpful style critique, no need to check against 0.
          delete [] myArray;
      }
  }
  </code></pre>
  
  <p>But now I want to create a dynamically allocated array of these classes. Here's my current code:</p>
  
  <pre><code>A* arrayOfAs = new A[5];
  for (int i = 0; i &lt; 5; ++i)
  {
      arrayOfAs[i] = A(3);
  }
  </code></pre>
  
  <p>But this blows up terribly. Because the new <code>A</code> object created (with the <code>A(3)</code> call) gets destructed when the <code>for</code> loop iteration finishes, and this means that the internal <code>myArray</code> of that <code>A</code> instance gets <code>delete []</code>-ed.</p>
  
  <p>So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:</p>
  
  <ul>
  <li>Creating a copy constructor for <code>A</code>.</li>
  <li>Using <code>vector&lt;int&gt;</code> and <code>vector&lt;A&gt;</code> so I don't have to worry about all this.</li>
  <li>Instead of having <code>arrayOfAs</code> be an array of <code>A</code> objects, have it be an array of <code>A*</code> pointers.</li>
  </ul>
  
  <p>I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.</p>
  
  <p>(Also, style critiques appreciated, since it's been a while since I did C++.)</p>
  
  <p><strong>Update for future viewers</strong>: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why <code>vector</code>s are a good way to go.</p>