Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perhaps consider using __attribute__((cleanup()) on GCC? #1

Open
TheLoneWolfling opened this issue Jun 1, 2020 · 1 comment
Open

Comments

@TheLoneWolfling
Copy link

GCC (& Clang) have a variable attribute that runs a function when a variable goes out of scope.

This allows for writing a with that handles return statements and such properly.

A quick example of the underlying concept:

#include "stdio.h"

void write_samples(const char *path, int numSamples, const float *samples)
{
    // Mild annoyance - cleanup takes a pointer to the variable.
    // Which you need to plumb through if the cleanup function takes it by value.
    void cleanup(FILE **f) {fclose(*f);}
    // nested functions are another GNUism. In C++11 or later you could use a lambda instead.
    FILE *fp __attribute__((cleanup(cleanup))) = fopen(path, "wb");
    fprintf(fp, "%d\n", numSamples);
    if (ferror(fp))
        return;
    for (int i = 0; i < numSamples; i++)
        fprintf(fp, "%f\n", samples[i]);
}

(In C++ replace the nested function with a lambda.)

In C++ this even handles exceptions sanely (read: runs the cleanup as part of exception handling).

@taeber
Copy link
Owner

taeber commented Jun 1, 2020

Thank you @TheLoneWolfling for providing an example of the cleanup attribute. I had mentioned it along with MSVC's try-finally as common alternatives in the README, but I know examples are helpful.

I'm assuming you are coming from Hacker News. I'll leave this issue open in case other people want to comment.

Thanks again. Take care!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants