首页IT科技自定义怎么删除掉(自定义删除器)

自定义怎么删除掉(自定义删除器)

时间2025-04-30 07:43:34分类IT科技浏览7702
导读:unique_ptr的成员函数在上一篇博客中几乎全部涵盖,其实还有一个很有踢掉,即std::unique_ptr::get_deleter字面已经很明显了,就获得deleter...

unique_ptr的成员函数在上一篇博客中几乎全部涵盖              ,其实还有一个很有踢掉                      ,即std::unique_ptr::get_deleter字面已经很明显了       ,就获得deleter

智能指针采通过引用计数我们能解决多次释放同一块内存空间的问题              ,并且和之间直接移交管理权的方式比较这种方式更加灵活安全               。

但是这种方式也只能处理new出来的空间因为new要和析构中的delete匹配                      ,为了使能和new,malloc       ,fopen的管理空间匹配       ,我们需要定制删除器

通过自定义删除器,可以实现一些场景下的资源释放和删除.

代码1

#include <iostream> #include <thread> using namespace std; template <typename T> class MyArrayDeletor { public: void operator()(T *p ){ cout << "call MyArrayDeletor" << endl; delete[] p; p = nullptr; } }; int main() { { unique_ptr<int, MyArrayDeletor<int>> ptr(new int[100]); } system("pause"); return 0; }

自定义删除器

代码2,删除器_文件

#include <iostream> #include <thread> using namespace std; template <typename T> class MyFileDeletor { public: void operator()(T *p) const { cout << "call MyFileDeletor" << endl; fclose(p); p = nullptr; } }; int main() { { unique_ptr<FILE, MyFileDeletor<FILE>> ptr(fopen("2.txt","w")); } system("pause"); return 0; }

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
服务器 美国 法律保护(美国服务器网络安全漏洞有哪些) 怎么恢复微信的语音聊天记录(如何恢复微信语音聊天记录)