如何从原始C堆内存指针初始化unique_ptr?[重复]

问题描述 投票:0回答:1

我正在使用一个函数(它是一个库的一部分),它返回一个原始的 uint8_t* 指针,指向堆上分配的一些内存,并保存图像像素数据。此函数的调用者负责调用 free 的指针上。

我的代码中,我调用这个函数的地方有很多分支,并且有提前终止的情况,因此我需要调用 free(buffer) 在很多时候。我想如果能把缓冲区用 unique_ptr 以便当它掉出范围时,自动释放内存。

如何实现这个功能呢?

作为参考,函数的声明是这样的。uint8_t* getFrame() (我已经知道了图像的宽度,高度,和num通道 以及缓冲区的长度);

c++ heap-memory smart-pointers unique-ptr raw-pointer
1个回答
5
投票

这是很简单的事情! 这个函数的模板是 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)}; 
}
© www.soinside.com 2019 - 2024. All rights reserved.