title: Using shared pointers with memory allocated in another function
body: <p>I have some legacy-era code at work that takes in a double-pointer and allocates memory to it. A shortened example of it would look something like this:</p>
  
  <pre><code>struct LegacyObj
  {
      int a;
      double b;
  };
  
  void LegacyAllocator(LegacyObj** ppObj)
  {
      *ppObj = (LegacyObj*)malloc(sizeof(LegacyObj));
  }
  
  void LegacyDeleter(LegacyObj** ppObj)
  {
      free(*ppObj);
  }
  </code></pre>
  
  <p>The actual LegacyAllocator function is ~100 lines and mixes reading from files with creating a linked list of LegacyObj pointers, and isn't something I'd be able to get away with rewriting right now. I would like, however, to make the use of this function a bit safer, avoiding any memory leaks that may occur from exceptions &amp;tc. The first solution I came up with was to wrap it up in a class and handle calling the legacy functions in the ctor/dtor.</p>
  
  <pre><code>class RAIIWrapper
  {
  public:
      RAIIWrapper()
          :obj{nullptr}
      {
          ::LegacyAllocator(&amp;obj);
      }
      RAIIWrapper(RAIIWrapper&amp;&amp; that)
          : obj{ that.obj}
      {
          that.obj = nullptr;
      }
      RAIIWrapper&amp; operator=(RAIIWrapper&amp;&amp; that)
      {
          RAIIWrapper copy{std::move(that)};
          std::swap(obj, copy.obj);
          return *this;
      }
      ~RAIIWrapper ()
      {
          ::LegacyDeleter(&amp;obj);
      }
  
  private:
      LegacyObj* obj;
  };
  </code></pre>
  
  <p>But I'm curious - is there a way to do this using <code>std::shared_ptr</code> or <code>std::unique_ptr</code>? I've not been able to come up with a solution without having to keep the original pointer passed to LegacyAllocator around.</p>