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;
}