如何将非静态成员函数作为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)
{
}
}
编译器不断抱怨No matching constructor for initialization of 'std::unique_ptr<CURL, void (*)(CURL *)>'
在我看来,删除器模板参数的声明是正确的。它是一个返回 void 的函数指针,并将 CURL * 作为参数。这与del_curl
的签名相匹配。
C++中是否有另一个我不知道的随机规则指定了对非静态成员函数指针的模板参数的要求?如果是这样,为什么?
@R. Sahu 的答案是正确的 imo。但是,如果您坚持传递非静态成员函数删除器,这里有一种使用旧std::bind
和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
,我想知道是否可以改进一下。
使用λ:
Foo(): _up(new int[42],
[this](int* p)->void
{
deleter(p);
}
){}
uptr_curl_
声明中使用的第二个模板参数是void (*)(CURL *)
&client::del_curl
的类型是 void (CURL::*)(CURL*)
.
它们是不一样的。可以将del_curl
更改为static
成员函数。这将解决问题。
更新
您可以在 std::function
和 std::bind
的帮助下使用非static
成员函数。
class client
{
public:
client();
private:
std::unique_ptr<CURL, std::function<void(CURL *)>> uptr_curl_;
CURL * init_curl();
void del_curl(CURL * ptr_curl);
};
client::client() : uptr_curl_(init_curl(),
std::bind(&client::del_curl, this, std::placeholders::_1))
{
// ...
}
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 删除[] 的行为 (ptr, 0)
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- 如何从集合中删除共享的 PTR 元素
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 删除PTR C 后会发生什么
- 如何删除带有 int ptr 指向它的数组
- 数据突然从 Boost shared_array/ptr 中删除
- c++中新建和删除ptr包装器类
- 删除ptr时堆损坏
- openv Ptr类.指针对象在调用函数后被删除
- 删除从函数返回的唯一ptr
- 当可以在类对象超出范围之前删除此数据时,类允许访问其数据(通过 ptr/it)是否设计不好