[英]std::unique_ptr custom deleter that takes two arguments
我正在处理以传统 C 风格完成内存分配/释放的遗留代码,但想用自定义删除器将其包装在 unique_ptr 中。 考虑一个二维数组通过调用 calloc/malloc 由遗留代码分配的情况。 我需要使用两个参数调用相应的旧版释放器函数——指向数组的指针和数组的大小。 在这种情况下,如何定义一个带有 2 个参数的自定义删除器,这两个参数都将仅在初始化 unique_ptr 以获取已分配数组的所有权时传递? 提前致谢。
下面是一个简化的(但人为的)示例:
// function allocates memory and returns size of the buffer
void legacyFunction(char **array, int *num)
{
char *p = (char *)calloc(5, sizeof(char));
for (auto i=0; i<5; ++i)
{
p[i] = 'a';
}
*num = 5;
*array = p;
return;
}
int main()
{
char *array = nullptr;
int numofElts = 0;
legacyFunction(&array, &numofElts);
// unique_ptr here to take ownership of array
// custom deleter should take both pointer and size
// the size could be any number based on business use case
return 0;
}
删除器是一个对象。 它可以保持大小。
struct LegacyDeleter
{
int size;
void operator()(char** ptr) const noexcept
{ legacyDeallocate(ptr, size); }
};
using legacy_ptr = std::unique_ptr<char*, LegacyDeleter>;
int main()
{
legacy_ptr ptr(legacyAllocatorFunction(5), LegacyDeleter{5});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.