Almost all C-type objects from C-libraries have some custom deleters, e.g. IplImage*
from OpenCV has the cvReleaseImage(IplImage**)
deleter function. In C++, I want my code in a way that it always ensures that every object gets finally deleted.
I guess it makes most sense to somehow use std::shared_ptr
and its custom deleter functionality.
One example / maybe possible solution is in this question where I would just use shared_ptr<IplImage>
but with a specialised version of default_delete<IplImage>
. But see the answers there about the drawbacks: it is not guaranteed by the C++ standard that shared_ptr
will use default_delete
as the default deleter and I'm not allowed to specialize default_delete
as I wish (see here).
Another solution would be something like this:
shared_ptr<IplImage> makeIplImage(IplImage* ptr) {
return shared_ptr<IplImage>(ptr, default_delete<IplImage>()); // using my specialised default_delete
}
But then I must be careful to never forget to call makeIplImage
when I want to wrap my IplImage*
.
Again another solution would be to write my own wrapper object class, like
class IplImageObj {
shared_ptr<IplImage> ptr;
public:
IplImageObj(IplImage* img) : ptr(img, default_delete<IplImage>()) {} // again using my specialised default_delete
// ...
};
I haven't really seen that much such solutions in the wild. Is it a bad idea to use them? If so, then I guess I'm missing something, but what? Or what is the most common/senseful way?