You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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"voidwrite_samples(constchar*path, intnumSamples, constfloat*samples)
{
// Mild annoyance - cleanup takes a pointer to the variable.// Which you need to plumb through if the cleanup function takes it by value.voidcleanup(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 (inti=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).
The text was updated successfully, but these errors were encountered:
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.
GCC (& Clang) have a variable attribute that runs a function when a variable goes out of scope.
This allows for writing a
with
that handlesreturn
statements and such properly.A quick example of the underlying concept:
(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).
The text was updated successfully, but these errors were encountered: