title: Can you use a shared_ptr for RAII of C-style arrays?
body: <p>I'm working on a section of code that has many possible failure points which cause it to exit the function early.  The libraries I'm interacting with require that C-style arrays be passed to the functions.  So, instead of calling delete on the arrays at every exit point, I'm doing this:</p>
  
  <pre><code>void SomeFunction(int arrayLength)
  {
     shared_ptr&lt;char&gt; raiiArray(new char[arrayLength]);
     pArray = raiiArray.get();
  
     if(SomeFunctionThatRequiresCArray(pArray) == FAILED) { return; }
  
     //etc.
  }
  </code></pre>
  
  <p>I wanted to use <code>unique_ptr</code>, but my current compiler doesn't support it and the reference count overhead doesn't really matter in this case.</p>
  
  <p>I'm just wondering if anyone has any thoughts on this practice when interfacing with legacy code.</p>
  
  <p><strong>UPDATE</strong>  I completely forgot about the <code>shared_ptr</code> calling <code>delete</code> instead of <code>delete []</code>.  I just saw no memory leaks and decided to go with it.  Didn't even think to use a vector.  Since I've been delving into new (for me) C++ lately I'm thinking I've got a case of the "If the only tool you have is a hammer, everything looks like a nail." syndrome.  Thanks for the feedback.</p>
  
  <p><strong>UPDATE2</strong> I figured I'd change the question and provide an answer to make it a little more valuable to someone making the same mistake I did.  Although there are alternatives like <code>scoped_array</code>, <code>shared_array</code> and <code>vector</code>, you can use a <code>shared_ptr</code> to manage scope of an array (but after this I have no idea why I would want to):</p>
  
  <pre><code>template &lt;typename T&gt;
      class ArrayDeleter
      {
      public:
          void operator () (T* d) const
          {
              delete [] d;
          }
      };
  
  void SomeFunction(int arrayLength)
      {
         shared_ptr&lt;char&gt; raiiArray(new char[arrayLength], ArrayDeleter&lt;char&gt;());
         pArray = raiiArray.get();
  
         if(SomeFunctionThatRequiresCArray(pArray) == FAILED) { return; }
  
         //etc.
      }
  </code></pre>