title: Swapping an object within itself
body: <p>I'm trying to swap an object within itself. It works but when I add a destructor it gives me a double free error. Is there a way to prevent this? The method I'm talking about is <code>void swap(SimpleArray &amp;object)</code>.</p>
  
  <p>(Sorry if you read this before I had the wrong info in my post...)</p>
  
  <pre><code>#include "TestType.h"
  class SimpleArray {
  
      private: 
          TestType* pArray;
          //TestType* temp;
      public:
          SimpleArray(TestType *array)
          {
              this-&gt;pArray = array;
          }
          ~SimpleArray() { delete[] pArray; }
          SimpleArray() { pArray = 0;}
          SimpleArray(const SimpleArray&amp; arg){ pArray = arg.pArray; }
          ~SimpleArray() { delete[] pArray; }
          TestType * get() const{ return pArray; }
          bool isNonNull() const { return pArray != 0; }
          //TestType* pArray;
          void reset(TestType*&amp; p) {this-&gt;pArray = p; }
          void reset() { pArray = 0; }
  
          void swap(SimpleArray &amp;object) { SimpleArray temp; temp = object; object = *this; *this = temp;}
          TestType * release() { pArray = 0; return pArray; }
          TestType&amp; getReference(int a) { return *pArray; }
  
  
  };
  </code></pre>
  
  <p>This works but once I add the destructor it gives me a "double free or corruption error". How do I solve this? Here's the function in main where it messes up.</p>
  
  <pre><code>bool testGetReleaseSwap() {
      SimpleArray array1;
      if (array1.get() != 0)
          return false;
  
      TestType* directArray1 = new TestType[100];
      array1.reset(directArray1);
      if (array1.get() != directArray1)
          return false;
  
      TestType* directArray2 = new TestType[50];
      SimpleArray array2(directArray2);
  
      array1.swap(array2);
      if (array1.get() != directArray2 || array2.get() != directArray1)
          return false;
  
      array2.swap(array1);
      if (array1.get() != directArray1 || array2.get() != directArray2)
          return false;
  
      array1.swap(array1);
      if (array1.get() != directArray1)
          return false;
  
      if (array1.release() != directArray1 || array2.release() != directArray2)
          return false;
  
      if (array1.get() != 0 || array2.get() != 0)
          return false;
  
      delete[] directArray1;
      delete[] directArray2;
  
      return true;
  }
  </code></pre>