-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_delete_fclose.cpp
47 lines (40 loc) · 1.36 KB
/
custom_delete_fclose.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*****************************************************************//**
* \file custom_delete_fclose.cpp
* \brief Foe some reason, the code base you are working with is stuck
* with an C-style file open-close operation, which needs explicit
* calling, otherwise resouces will be leaked.
* Consider combination of a custom deleter with smart pointers.
*
* `enable_shared_from_this` and `this->shared_from_this();`
*
* $ cd .\CustomDeleter\
* $ cmake ..\CMakeLists.txt
*
* \author Xuhua Huang
* \date December 01, 2022
*********************************************************************/
#include <stdio.h>
#include <iostream>
#include <memory>
struct fclose_deleter {
// type of Deleter must have an operator()(T*)
void operator()(FILE* fp) const { fclose(fp); }
};
int main(void) {
using unique_file = std::unique_ptr<FILE, fclose_deleter>;
// creating an inner svope for demonstration purpose
char* buffer{};
size_t N = 0;
{
unique_file fp(fopen("./CMakeLists.txt", "r"));
fread(buffer, 1, N, fp.get());
/* with std::shared_ptr */
// std::shared_ptr<FILE> shared_fp(
// fopen("CMakeLists.txt", "r"),
// fclose_deleter{}
// );
} // when the unique_ptr<T> goes out of the scope
// fclose will be called automatically
system("pause");
return EXIT_SUCCESS;
}