Having two functions for allocation and freeing a raw pointer, I want to use C++ to get dirty job done easily. I found two options to make unique_ptr
handle it and neither of them looks good to me:
char *raw_alloc();
void raw_free(char *ptr);
int main (int argc, char *argv[])
{
//First option:
{
std::unique_ptr<char, decltype(&raw_free)> ptr (raw_alloc(), raw_free);
printf ("size1: %lu\n", sizeof(ptr) / sizeof(char *));
}
//Second option:
{
struct deleter { void operator()(char *ptr) { raw_free(ptr); } };
std::unique_ptr<char, deleter> ptr (raw_alloc());
printf ("size2: %lu\n", sizeof(ptr) / sizeof(char *));
}
}
Output says that the first pointer is twice as large as the second; naturally it takes space to keep a pointer to the freeing function.
In the same time second option requires me to create stub deleter for my type. Of course, I can write a function template that does it for me:
template <typename T, void (*D)(T*)>
auto my_unique (T *ptr) {
struct deleter { void operator()(T *ptr) { D(ptr); } };
return unique_ptr<T,deleter>(ptr);
};
But why can't unique_ptr
do it for me and just accept deleter function as second template argument? How do skilled C++ people handle raw pointers?