Defer Implementation in C
The concept of Go-style defer, which allows for clean and concise resource cleanup, has gained popularity in C . However, finding a standard or well-supported library implementation for this feature can be challenging.
Despite the absence of built-in support for defer in the Standard Template Library (STL) or Boost, there are external implementations available. One such implementation is a lightweight, zero-overhead solution:
<code class="cpp">#ifndef defer 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{} *[&]() #endif // defer</code>
This implementation requires minimal setup and can be easily integrated into your codebase. The syntax is straightforward:
<code class="cpp">defer { statements; };</code>
For example, in the following code snippet, the fclose operation is automatically executed when the scope of the read_entire_file function is exited:
<code class="cpp">auto file = std::fopen(filename, "rb"); if (!file) return false; defer { std::fclose(file); }; // don't need to write an RAII file wrapper. // ...</code>
This zero-overhead implementation offers a convenient and efficient way to manage resource cleanup in C , providing a Go-like defer feature without the need for complex RAII classes or custom memory management techniques.
The above is the detailed content of How to Achieve Go-Style Defer in C Without Sacrificing Performance?. For more information, please follow other related articles on the PHP Chinese website!