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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540093.html
標籤:C++
上一篇:<六>無序關聯容器
