std::unique_ptr用于包装malloc指针的自定义删除器

huangapple go评论58阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月12日 13:40:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定