I’m trying to use libsvm 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:
struct svm_model *model;
model = svm_load_model("path to model file");
//do some processing
svm_free_and_destroy_model(&this->model);
And these are the definitions of the libsvm API functions that I used:
struct svm_model *svm_load_model(const char *model_file_name);
void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
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 svm_load_model in the constructor and svm_free_and_destroy_model in the destructor.
Now, since we are in the era of smart pointers, I was thinking to get a bit more creative, and, somehow, declare the model variable as an std::unique_ptr, setting a pointer to svm_free_and_destroy_model 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:
std::unique_ptr<struct svm_model *, /* what should I add here? */ > model (svm_load_model("path to model file"), svm_free_and_destroy_model);
The type argument to
std::unique_ptrneeds to beT, notT *. Use a lambda to call the deleter function.Since VS2010 does not implement conversion of stateless lambdas to function pointers, you’ll have to use
std::functionto get this to work.