example3_custom_deleter.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
#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::unique_ptr<FILE, FileDeleter> filePtr(std::fopen("example.txt", "w"));

    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_unique_ptr