Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr with custom deleter for wrapping a malloc pointer

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++?

like image 943
D.J. Elkind Avatar asked Oct 25 '25 06:10

D.J. Elkind


1 Answers

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.

like image 111
Sebastian Redl Avatar answered Oct 26 '25 21:10

Sebastian Redl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!