包装RAII的C分配 [英] Wrap C allocation for RAII
本文介绍了包装RAII的C分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从库中获得了这些普通的C函数:
I've these plain C functions from a library:
struct SAlloc;
SAlloc *new_salloc();
void free_salloc(SAlloc *s);
有什么方法可以用C ++将其包装到智能指针(std :: unique_ptr),还是RAII包装器?
Is there any way I can wrap this in C++ to a smart pointer (std::unique_ptr), or otherwise a RAII wrapper ?
我主要是对标准库的可能性感到好奇,而没有创建自己的包装器/类。
I'm mainly curious about the possibilities of the standard library without creating my own wrapper/class.
推荐答案
是的,您可以为此重复使用unique_ptr。只需创建一个自定义删除器即可。
Yes, you can reuse unique_ptr for this. Just make a custom deleter.
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>;
这篇关于包装RAII的C分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文