我使用这种对象的自定义删除模板。
template<typename T, T Function>
struct function_deleter
{
template<typename U>
auto operator()(U&& u) const noexcept(noexcept(Function(std::forward<U>(u))))
{
return Function(std::forward<U>(u));
}
};
,那么你可以使用你的电话删除者free
:
unique_ptr<int, function_deleter<void(*)(void*), &free>> uniq;
而且其规模仍然等于一个指针。 live demo
快来C++ 17,你就可以使用auto
非类型模板参数,代码简化到:
template<auto Function>
struct function_deleter
{
template<typename U>
auto operator()(U&& u) const noexcept(noexcept(Function(std::forward<U>(u))))
{
return Function(std::forward<U>(u));
}
};
和
unique_ptr<int, function_deleter<&call_free>> uniq;
live demo
有了这个,在你的情况下,我会保持unique_ptr<pair<lib_object, lib_api>>
静态删除器支持这种结构。
using lib_pair = pair<lib_object, lib_api>;
void lib_free(lib_pair* p){
p->second.freeInstance(p->first);
delete p;
}
using unique_lib_ptr = unique_ptr<lib_pair, function_deleter<void(*)(lib_pair*), &lib_free>>
这似乎更加缓存繁重,但可能只是你的东西。
你可以让'lib_api *'成为deleter类的静态成员吗? – Brian
我认为你需要将'freeInstance'存储在容器类的自定义派生类中,并且你的容器将包含'lib_object *'。在派生类中,您必须实现将在每个元素上调用'freeInstance'的析构函数。 – Franck