为RAII包裹C分配

use*_*970 7 c++ smart-pointers c++11

我从库中获得了这些普通的C函数:

struct SAlloc;
SAlloc *new_salloc();
void   free_salloc(SAlloc *s);
Run Code Online (Sandbox Code Playgroud)

有什么方法可以用C++将它包装成智能指针(std :: unique_ptr),或者RAII包装器吗?

我主要是对标准库的可能性感到好奇而没有创建我自己的包装器/类.

R. *_*des 14

是的,您可以为此重用unique_ptr.只需制作自定义删除器.

struct salloc_deleter {
    void operator()(SAlloc* s) const {
        free_salloc(s); // what the heck is the return value for?
    }
}

using salloc_ptr = std::unique_ptr<SAlloc, salloc_deleter>;
Run Code Online (Sandbox Code Playgroud)