"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Go-Style Defer in C++ Without Sacrificing Performance?

How to Achieve Go-Style Defer in C++ Without Sacrificing Performance?

Published on 2024-11-16
Browse:477

How to Achieve Go-Style Defer in C   Without Sacrificing Performance?

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:

#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

This implementation requires minimal setup and can be easily integrated into your codebase. The syntax is straightforward:

defer { statements; };

For example, in the following code snippet, the fclose operation is automatically executed when the scope of the read_entire_file function is exited:

auto file = std::fopen(filename, "rb");
if (!file)
    return false;

defer { std::fclose(file); }; // don't need to write an RAII file wrapper.

// ...

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.

Latest tutorial More>

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