-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
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
Labels
No labels