title: Using std::unique_ptr with a custom deallocator for wrapping raw pointers
body: <p>I'm trying to use <a href="http://www.csie.ntu.edu.tw/~cjlin/libsvm/" rel="nofollow">libsvm</a> for a certain complex application and, because libsvm is, mostly, a C library, one has to use a custom API function to release memory, after loading certain data. Here is what I mean:</p>
  
  <pre><code>struct svm_model *model;
  model = svm_load_model("path to model file");
  
  //do some processing
  
  svm_free_and_destroy_model(&amp;this-&gt;model);
  </code></pre>
  
  <p>And these are the definitions of the libsvm API functions that I used:</p>
  
  <pre><code>struct svm_model *svm_load_model(const char *model_file_name);
  void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
  </code></pre>
  
  <p>Although this works just fine, if an exception occurs while I process the model data, then I'll end up with memory leaks. To prevent this, I wrapped the above code in a class, where I call <code>svm_load_model</code> in the constructor and <code>svm_free_and_destroy_model</code> in the destructor.</p>
  
  <p>Now, since we are in the era of <strong>smart pointers</strong>, I was thinking to get a bit more creative, and, somehow, declare the model variable as an <code>std::unique_ptr</code>, setting a pointer to <code>svm_free_and_destroy_model</code> as the custom deallocator, but, unfortunately, I'm not able to figure out if such a thing is doable. At the moment, I'm not even able to make it compile and I'm just shooting in the dark. Here is how I think it should work:</p>
  
  <pre><code>std::unique_ptr&lt;struct svm_model *, /* what should I add here? */ &gt; model (svm_load_model("path to model file"), svm_free_and_destroy_model);
  </code></pre>