Question

I have the following code:

Gdiplus::Image image(filename.c_str());
UINT size = image.GetPropertyItemSize(PropertyTagExifDTOrig);
Gdiplus::PropertyItem* propertyItem = (Gdiplus::PropertyItem*)malloc(size);

The problem is that the code after this branches based on several different conditions. So I'd like to use something like std::unique_ptr to ensure the pointer on the last line gets deleted, no matter where my code branches.

However, it doesn't appear that std::unique_ptr can easily be implemented here. It seems to require a fixed-size type, and doesn't support a custom size.

Is this right? Is there any good way to implement an automatic pointer here?

Was it helpful?

Solution

std::unique_ptr supports a custom deleter. Since you're allocating with malloc, you can use free:

std::unique_ptr<Gdiplus::PropertyItem, void (*)(void*)> propertyItem{
    (Gdiplus::PropertyItem*) std::malloc(size), &std::free};

If you prefer to avoid passing the deleter, you can create a struct that does the deletion for you:

struct FreeDeleter {
  void operator()(void* p) {
    std::free(p);
  }
};

std::unique_ptr<Gdiplus::PropertyItem, FreeDeleter> propertyItem{
    (Gdiplus::PropertyItem*) std::malloc(size)};

OTHER TIPS

std::unique_ptr<Gdiplus::PropertyItem[]> pitem(new Gdiplus::PropertyItem[size]);

std::unique_ptr<Gdiplus::PropertyItem[]> pitem = std::make_unique<Gdiplus::PropertyItem[]>(size);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top