Custom Implementation of a "Defer" Feature in C
In C , the concept of "defer" involves executing specific actions at the end of a particular scope or block of code. While the STL (Standard Template Library) and Boost libraries do not provide a built-in implementation of this feature, a custom solution can be created using the following code snippet:
#ifndef defer
struct defer_dummy {};
template struct deferrer { F f; ~deferrer() { f(); } };
template deferrer operator*(defer_dummy, F f) { return {f}; }
#define DEFER_(LINE) zz_defer##LINE
#define DEFER(LINE) DEFER_(LINE)
#define defer auto DEFER(__LINE__) = defer_dummy{} *[&]()
#endif // defer
Usage:
The defer macro can be used within a specific scope to define a block of code that will be executed when that scope ends. The syntax is as follows:
defer {
// Code to be executed at the end of the current scope
};
Example:
In the following example, the defer macro is used within the read_entire_file function to automatically close the input file when the function exits:
#include
#include
bool read_entire_file(char *filename, std::uint8_t *&data_out, std::size_t *size_out = nullptr) {
if (!filename)
return false;
auto file = std::fopen(filename, "rb");
if (!file)
return false;
defer { std::fclose(file); }; // don't need to write an RAII file wrapper.
// ... Remaining code
}
Benefits:
Note:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3