我正在使用一个函数(它是一个库的一部分),它返回一个原始的 uint8_t*
指针,指向堆上分配的一些内存,并保存图像像素数据。此函数的调用者负责调用 free
的指针上。
我的代码中,我调用这个函数的地方有很多分支,并且有提前终止的情况,因此我需要调用 free(buffer)
在很多时候。我想如果能把缓冲区用 unique_ptr
以便当它掉出范围时,自动释放内存。
如何实现这个功能呢?
作为参考,函数的声明是这样的。uint8_t* getFrame()
(我已经知道了图像的宽度,高度,和num通道 以及缓冲区的长度);
这是很简单的事情! 这个函数的模板是 std::unique_ptr
看起来像这样。
template<class T, class Deleter>
class unique_ptr;
而Deleter是用来清理这个值的 unique_ptr
当它落在范围之外时。我们可以写一个来使用 free
真的很简单!
struct DeleteByFree {
void operator()(void* ptr) const {
free(ptr);
}
};
template<class T>
using my_unique_ptr = std::unique_ptr<T, DeleteByFree>;
现在,每当你使用 my_unique_ptr
它将调用C的 free()
功能来清理自己!
int main(){
// This gets cleaned up through `free`
my_unique_ptr<int> ptr {(int*)malloc(4)};
}