Can C achieve Go-style Defer Functionality with Minimal Overhead?

Patricia Arquette
Release: 2024-11-01 20:07:30
Original
149 people have browsed it

Can C   achieve Go-style Defer Functionality with Minimal Overhead?

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>
Copy after login

Usage

This implementation is used in the same way as the Go language Delay syntax is similar:

<code class="cpp">defer {
    // 要在函数退出时执行的代码块
};</code>
Copy after login

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>
Copy after login

Advantages

  • None Overhead: This implementation introduces no additional overhead, unlike other object or smart pointer based implementations.
  • Easy syntax: The syntax mimics the lazy syntax of Go language, making the code clearer and easier to read.
  • Zero Dependencies: The implementation is completely self-contained and does not increase compilation time.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!