nemequ / hedley

A C/C++ header to help move #ifdefs out of your code
https://nemequ.github.io/hedley/
Creative Commons Zero v1.0 Universal
774 stars 51 forks source link

Add support for finally macro / function #36

Closed tapika closed 4 years ago

tapika commented 4 years ago

https://docs.microsoft.com/en-us/cpp/cpp/try-finally-statement?view=vs-2019

Microsoft compiler provides special syntax for using try - finally, but it's Microsoft specific. Is it possible to do same support for other compilers as well,

ideas on how to do it could be borrowed from here: https://stackoverflow.com/questions/161177/does-c-support-finally-blocks-and-whats-this-raii-i-keep-hearing-about

or self made implementation.

Wondering when this comes into C++ standards....

nemequ commented 4 years ago

While this might work in C++ (I'd have to do a bit more research), it definitely wouldn't work in C. You could do something similar with GCC's cleanup variable attribute, but the syntax would be pretty different and we definitely couldn't hide it in a macro.

Since this significantly alters the behavior of the code {see the Can you add support for «feature»? question in the FAQ) it's not a good fit for Hedley. Perhaps it would be better suited to Boost?

Quuxplusone commented 2 years ago

FWIW, you could use the technique shown in https://www.club.cc.cmu.edu/~ajo/disseminate/auto.h . This macro allows writing constructions like this:

#include <stdio.h>
#include "auto.h"
int main() {
    bool committed = false;
    Auto(puts("goodbye"));
    Auto(if (!committed) { puts("rollback"); });
    puts("hello world");
    committed = true;
}  // at this point "goodbye" is printed