Is it possible to use object type and free functions as parameters for creating custom deleters for std::unique_ptr
?
I'm new to templates and came up till here:
#include <memory>
template<typename T, typename FreeFunc> struct ObjectDeleter {
const FreeFunc &free_func;
ObjectDeleter(const FreeFunc &free_func) : free_func(free_func){
}
void operator()(T *item)
{
if (item) {
free_func(item);
}
}
};
struct Foo{};
void internal_foo_free(Foo *){}
struct Bar{};
void internal_bar_free(Bar *){}
using unique_foo_ptr =
std::unique_ptr<Foo, ObjectDeleter<Foo>([](Foo *foo){internal_foo_free(foo);});
int main(){
return 0;
}
error:
<source>:19:48: error: wrong number of template arguments (1, should be 2)
19 | std::unique_ptr<Foo, ObjectDeleter<Foo>([](Foo *foo){internal_foo_free(foo);});
| ^
<source>:3:48: note: provided for 'template<class T, class FreeFunc> struct ObjectDeleter'
3 | template<typename T, typename FreeFunc> struct ObjectDeleter {
| ^~~~~~~~~~~~~
<source>:19:50: error: lambda-expression in template-argument only available with '-std=c++2a' or '-std=gnu++2a'
19 | std::unique_ptr<Foo, ObjectDeleter<Foo>([](Foo *foo){internal_foo_free(foo);});
| ^
<source>:19:87: error: template argument 2 is invalid
19 | std::unique_ptr<Foo, ObjectDeleter<Foo>([](Foo *foo){internal_foo_free(foo);});
| ^
Compiler returned: 1
I was suggested to use function pointer (and I extend it to std::function also):
but that adds the possibility of adding throwing statements via the function pointer (or std::function), which the compiler or static analysers won't be able to detect. Parameterising using lambda will make sure that the no-one can add throwing statements in the destructor of std::unique_ptr. This is what I mean by "noexcept-detectable, callable object"
I'm using C++17.