std::unique_ptr for C functions that need free

What you have is extremely likely to work in practice, but not strictly correct. You can make it even more likely to work as follows:

std::unique_ptr<char, decltype(std::free) *>
    t_copy { strdup(t), std::free };

The reason is that the function type of std::free is not guaranteed to be void(void*). It is guaranteed to be callable when passed a void*, and in that case to return void, but there are at least two function types that match that specification: one with C linkage, and one with C++ linkage. Most compilers pay no attention to that, but for correctness, you should avoid making assumptions about it.

However, even then, this is not strictly correct. As pointed out by @PeterSom in the comments, C++ allows implementations to e.g. make std::free an overloaded function, in which case both your and my use of std::free would be ambiguous. This is not a specific permission granted for std::free, it’s a permission granted for pretty much any standard library function. To avoid this problem, a custom function or functor (as in his answer) is required.

Assuming it makes sense, it is possible to use a similar pattern with non-pointers?

Not with unique_ptr, which is really specific to pointers. But you could create your own class, similar to unique_ptr, but without making assumptions about the object being wrapped.

Leave a Comment