在运行时确定大小的对象上使用std::unique_ptr
Using std::unique_ptr on Object whose Size is Determined at Run Time
我有以下代码:
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);
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 为什么 std::unique 不调用 std::sort?
- 我对 std::unique(算法)C++有问题
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++ std::unique并没有显示我对它的期望
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 是否可以在 std::unique<T[ ]> 上应用 std::sort?
- std::unique 是否有大小限制
- 从 std::unique 返回的迭代器的用法
- 使 std::unique<T> 与 std::unique<const T, CustomDeleterType 兼容>
- Std::list.unique()应该使迭代器无效
- 无法使用初始化器列表构造 vector<std::unique<...>>
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃
- 我能保证std::unique将保留第一个元素吗?
- 在 std::vector<std::unordered_set上使用 std::unique(<T>>