英文:
std::unique_ptr with custom deleter for wrapping a malloc pointer
问题
这个设计是正确的,并且遵循了在C++中将原始指针包装的最佳实践。
英文:
I have a C library function:
uint8_t* c_func();
This either returns a valid uint8_t
pointer allocated with malloc()
, or NULL
on error. I want to wrap it in a std::unique_ptr()
as follows:
struct FreeDeleter {
void operator()(void *p) const {
std::free(p);
}
};
template <typename T>
using unique_fptr = std::unique_ptr<T, FreeDeleter>;
std::free()
does nothing if the pointer being passed to it is NULL
, so this should work as expected.
Is this design correct, and does it follow the best practices of wrapping a raw pointer in C++?
答案1
得分: 4
是的,这是最佳实践。
我会再进一步,将C函数封装在一个函数中,该函数只需立即将结果封装在unique_ptr中,这样你就永远不会忘记这样做。
然而,要注意一个很大的警告!如果C函数位于Windows上的共享库中,它可能使用不同的堆,因此在主程序中使用free将是无效的。然而,除非库提供了自定义的free函数,否则你无法做任何事情,在这种情况下,你应该真正使用它。
英文:
Yes, this is best practice.
I would go one step further and wrap the C function in a function that just immediatly wraps the result in the unique_ptr, so that you can never forget to do it.
However, big caveat! If the C function is in a shared library on Windows, it might use a different heap and thus using free in your main program would be invalid. There's nothing you can do about that however unless the library provides its own custom free function, in which case you should really use that anyway.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论