Skip to content

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

@TheLoneWolfling

Description

@TheLoneWolfling

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions