How to wrap a char* from strdup() in a smart pointer to guarantee it gets freed?
#include <memory>
typedef std::unique_ptr<char, decltype(&std::free)> char_ptr;
char_ptr make_char_ptr(const std::string str)
{
return char_ptr(strdup(str.data()), std::free);
}
//...
char_ptr foo = make_char_ptr("bar");
foo.get(); // char* pointer to a copy of "bar"
// pointer automatically gets freed when 'foo' goes out of scope
// or can be freed manually with
foo.reset();