1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <memory>
#include <cstdio> // For FILE*
struct FileDeleter {
void operator()(FILE* fp) const {
if (fp) {
std::cout << "Closing file" << std::endl;
std::fclose(fp);
}
}
};
int main() {
std::shared_ptr<FILE> filePtr(std::fopen("example.txt", "w"), FileDeleter());
if (filePtr) {
std::fprintf(filePtr.get(), "Hello, file!\n");
}
// filePtr goes out of scope, and FileDeleter is invoked to close the file
return 0;
}
Back to std_shared_ptr