"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 can you implement a \"defer\" feature in C++ without relying on STL or Boost libraries?

How can you implement a \"defer\" feature in C++ without relying on STL or Boost libraries?

Published on 2025-01-27
Browse:645

How can you implement a \

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:

  • Zero overhead: Unlike some other implementations, this approach does not incur any additional overhead.
  • Syntactically concise: The syntax is designed to be easy to read and use.
  • Zero dependencies: This implementation does not rely on any external libraries, reducing compile times.
  • Flexible: The defer block can contain any valid C statement or expression.

Note:

  • The local deferrer object's name starts with zz_ instead of _ to avoid Namespace Pollution.
  • User identifiers should not technically begin with an underscore.
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