如何将非静态成员函数作为unique_ptr删除器传递 [英] How to pass a non-static member function as a unique_ptr deleter
问题描述
#include <memory>
#include <iostream>
#include <exception>
#include <curl/curl.h>
class client
{
private:
std::unique_ptr<CURL, decltype(&psclient::del_curl)> uptr_curl_;
inline CURL * init_curl()
{
CURLcode result = curl_global_init(CURL_GLOBAL_DEFAULT);
if(result != CURLE_OK)
throw std::logic_error(curl_easy_strerror(result));
return curl_easy_init();
}
inline void del_curl(CURL * ptr_curl)
{
curl_easy_cleanup(ptr_curl);
curl_global_cleanup();
}
public:
inline client()
: uptr_curl_(init_curl(), &client::del_curl)
{
}
}
编译器保持抱怨没有匹配的构造函数用于'std: :unique_ptr< CURL,void(*)(CURL *)>'
看起来像声明是正确的删除模板参数。它是一个函数指针,返回void,并以CURL *作为参数。这符合 del_curl
的签名。
It seems to me like the declaration is correct for the deleter template argument. It is a function pointer that returns void and takes a CURL * as an argument. This matches the signature of del_curl
.
在C ++中还有另一个随机规则,对非静态成员函数指针的模板参数的要求?如果是,为什么?
Is there yet another random rule, unknown to me, in C++ that specifies a requirement for template arguments to non-static member function pointers? If so, why?
推荐答案
@R的答案。 Sahu是正确的imo。但是,如果你坚持传递非静态成员函数deleter,这里是一个使用好旧的 std :: bind
和 std :: function
:
The answer of @R. Sahu is correct imo. However, if you insist of passing a non-static member function deleter, here is a way of doing it using the good old std::bind
and std::function
:
#include <memory>
#include <iostream>
#include <functional>
class Foo
{
private:
std::unique_ptr<int, std::function<void(int*)>> _up;
public:
Foo(): _up(new int[42], std::bind(&Foo::deleter, this, std::placeholders::_1))
{
}
void deleter(int* p)
{
delete[] p;
std::cout << "In deleter" << std::endl;
}
};
int main()
{
Foo foo;
}
PS:我只是不喜欢 bind
PS: I just don't like the bind
, I wonder if one can improve on that.
使用lambda:
Foo(): _up(new int[42],
[this](int* p)->void
{
deleter(p);
}
){}
这篇关于如何将非静态成员函数作为unique_ptr删除器传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!