title: C++ copy constructor with pointers
body: <p>I understand the need to deep copy pointers (in cases when you want a complete copy of an object), my confusion comes with the following (completely made up example).</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;string&gt;
  
  class a
  {
  public:
  
      a::a(std::string _sz) : 
          m_sz(_sz)
          ,m_piRandom(new int)
      {
          *m_piRandom = 1;
      };
  
      ~a()
      {
          delete m_piRandom;
          m_piRandom = NULL;
      };
  
      a::a(const a &amp;toCopy)
      {
          operator=(toCopy);
      }
  
      a&amp; a::operator=(const a &amp;toAssign)
      {
          if (this != &amp;toAssign)
          {
              m_sz = toAssign.m_sz;
              if (m_piRandom)
              {
                  // Need to free this memory! 
                  delete m_piRandom;
                  m_piRandom = NULL;
              }
  
              m_piRandom = new int(*toAssign.m_piRandom);
          }
          return *this;
      }
  
      void SetInt(int i)
      {
          if (!m_piRandom)
          {
              m_piRandom = new int;
          }
          *m_piRandom = i;
      }
  
  private:
  
      std::string m_sz;
      int* m_piRandom;
  };
  
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      a Orig = a("Original");
      a New = a("New"); 
      New.SetInt(9);
      New = Orig;
  
      return 0;
  }
  </code></pre>
  
  <p>Now in my example I want to test the scenario where I have an object with some memory allocated to it, in this case:</p>
  
  <pre><code>a New = a("New"); 
  New.SetInt(9); // This new's the memory
  </code></pre>
  
  <p>allocates the memory and then when we say: <code>New = Orig;</code> I would expect a memory leak because if I blindly new'd the <code>m_piRandom = new int(*toAssign.m_piRandom);</code> I would have lost the memory it was previously pointing to.. </p>
  
  <p>So I decided to put the following in the assignment operator:</p>
  
  <pre><code>if (m_piRandom)
              {
                  // Need to free this memory! 
                  delete m_piRandom;
                  m_piRandom = NULL;
              }
  </code></pre>
  
  <p>This crashes the code when the following is called (first line!) <code>a Orig = a("Original");</code> as it calls the copy constructor (which I call the assignment operator for less duplication) and the pointer <code>m_piRandom</code> is set to 0xcccccccc. Not NULL. Therefore it tries to delete memory that was never allocated. I would expect it to work when it got to the <code>New = Orig;</code> because it would delete it first before assigning the copy. Can anybody shed any light on this, I guess my biggest concern is that m_piRandom is not NULL, I also tried defining a default constructor for a which NULLs the pointer by default but this didn't help. Apologies for the completely contrived code..</p>
  
  <p>Thanks</p>