Defer in C++
Our first program demonstrates the use of defer, which is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. In C++, we can achieve similar functionality using RAII (Resource Acquisition Is Initialization) and smart pointers.
In this C++ version, we use a std::unique_ptr
with a custom deleter to mimic the behavior of defer. The FileDeleter
struct defines the cleanup action that will be performed when the unique_ptr
is destroyed.
The createFile
function returns a FilePtr
, which is a unique_ptr
to an ofstream
with our custom deleter. This ensures that the file will be properly closed when it goes out of scope, similar to how defer works in the original example.
The writeFile
function takes a reference to our FilePtr
and writes to the file.
In the main
function, we create the file and write to it. The file will be automatically closed when f
goes out of scope at the end of the try block, or if an exception is thrown.
To run the program:
This example demonstrates how to use RAII principles in C++ to achieve similar functionality to defer in other languages. The file is automatically closed at the end of the program’s execution, ensuring proper resource management.