在运行时确定大小的对象上使用std::unique_ptr

Using std::unique_ptr on Object whose Size is Determined at Run Time

本文关键字:std unique ptr 对象 运行时      更新时间:2023-10-16

我有以下代码:

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

问题是,在此之后的代码根据几个不同的条件进行分支。所以我想使用std::unique_ptr之类的东西来确保最后一行的指针被删除,无论我的代码分支在哪里。

然而,std::unique_ptr在这里似乎不容易实现。它似乎需要一个固定大小的类型,而不支持自定义大小。

这样对吗?有什么好方法来实现一个自动指针在这里?

std::unique_ptr支持自定义删除器。由于您正在使用malloc进行分配,因此可以使用free:

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

如果您不希望传递delete,则可以创建一个结构体来为您执行删除操作:

struct FreeDeleter {
  void operator()(void* p) {
    std::free(p);
  }
};
std::unique_ptr<Gdiplus::PropertyItem, FreeDeleter> propertyItem{
    (Gdiplus::PropertyItem*) std::malloc(size)};
std::unique_ptr<Gdiplus::PropertyItem[]> pitem(new Gdiplus::PropertyItem[size]);
std::unique_ptr<Gdiplus::PropertyItem[]> pitem = std::make_unique<Gdiplus::PropertyItem[]>(size);