I'm working on some code with unique_ptr
s and the like. The line is:
std::unique_ptr<char[], void(*)(void*)> result(..., std::free);
which works. I realize that the type that std::free gives is that second template parameter. I tried using:
std::unique_ptr<char[], decltype(std::free)> result(..., std::free);
which would be easier to read and less bug-prone. But I get errors related to <memory>
and "instantiating a data member with a function type".
Would there be a way to do this?
decltype(std::free)
yields the type of std::free
, which is the function type void(void*)
, not the function pointer type void(*)(void*)
. You need a function pointer type, which you can obtain by taking the address of std::free
:
std::unique_ptr<char[], decltype(&std::free)> result(..., std::free);
^
or by forming the function pointer type yourself:
std::unique_ptr<char[], decltype(std::free)*> result(..., std::free);
^
(I'd argue that the former is clearer.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With