如何从原始C堆内存指针初始化unique_ptr?

时间:2020-06-10 20:55:37

标签: c++ heap-memory smart-pointers unique-ptr raw-pointer

我正在使用一个函数(它是库的一部分),该函数将返回一个原始import os import time from datetime import datetime root = "/dbfs/mnt/datalake/.../LMMS16005/" a = time.ctime(max(os.path.getmtime(root) for root,_,_ in os.walk(root))) aa = datetime.strptime(a,'%a %B %d %H:%M:%S %Y').date() print(aa) 指针,该指针指向已在堆上分配并保存图像像素数据的某些内存。该函数的调用者负责在指针上调用uint8_t*

我在其中调用此函数的代码具有多个提前终止的分支,因此,我需要在许多地方调用free。我认为最好将缓冲区包装在free(buffer)中,以便在超出范围时自动释放内存。

我该如何实现?

作为参考,函数清理类似于以下内容:unique_ptr(我已经知道图像的宽度,高度和数量通道,因此知道缓冲区的长度);

1 个答案:

答案 0 :(得分:5)

这很简单! std::unique_ptr的模板如下:

template<class T, class Deleter>
class unique_ptr;

unique_ptr所指向的值超出范围时,使用Deleter清除它。我们可以写一个简单地使用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)}; 
}