Standard delay/terminator implementation in C
The delay function in Go language is a way to execute a block of code when the function exits Mechanism that simplifies resource cleanup and error handling. This article explores the possibility of a similar deferred implementation in C, and the feasibility of alternatives in existing libraries.
Existing implementations
The C standard library, Boost and other third-party libraries do not yet provide ready-made lazy implementations. However, the following lightweight custom implementation provides similar functionality to the Go language:
<code class="cpp">struct defer_dummy {}; template <class F> struct deferrer { F f; ~deferrer() { f(); } }; template <class F> deferrer<F> 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{} *[&]()</code>
Usage
This implementation is used in the same way as the Go language Delay syntax is similar:
<code class="cpp">defer { // 要在函数退出时执行的代码块 };</code>
Example Usage
<code class="cpp">#include <cstdio> #include <cstdlib> bool read_entire_file(char *filename, std::uint8_t *&data_out, std::size_t *size_out = nullptr) { auto file = std::fopen(filename, "rb"); if (!file) return false; defer { std::fclose(file); }; // 自动关闭文件 // ...其他文件操作代码 return true; } int main(int argc, char **argv) { if (argc < 2) return -1; std::uint8_t *file_data = nullptr; std::size_t file_size = 0; auto read_success = read_entire_file(argv[1], file_data, &file_size); defer { delete[] file_data; }; // 自动释放文件数据 if (read_success) { // ...文件处理代码 return 0; } else { return -1; } }</code>
Advantages
The above is the detailed content of Can C achieve Go-style Defer Functionality with Minimal Overhead?. For more information, please follow other related articles on the PHP Chinese website!