Last active
October 15, 2021 23:18
-
-
Save skaslev/4b6dd4166e5cc88a6721 to your computer and use it in GitHub Desktop.
Go-like defer statement for C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
namespace { | |
template<typename F> | |
class ScopeGuard { | |
public: | |
ScopeGuard(F f) : f_(f) { | |
} | |
~ScopeGuard() { | |
f_(); | |
} | |
private: | |
F f_; | |
}; | |
#define CAT_(a, b) a ## b | |
#define CAT(a, b) CAT_(a, b) | |
#define defer_(f, g, e) auto f = [&]() { e; }; ScopeGuard<decltype(f)> g(f) | |
#define defer(expr) defer_(CAT(f, __LINE__), CAT(guard, __LINE__), expr) | |
} // namespace | |
int main() { | |
FILE* f = fopen("defer.cpp", "r"); | |
if (!f) { | |
perror("fopen"); | |
exit(-1); | |
} | |
defer(fclose(f)); | |
defer(printf("Yep.\n")); | |
defer(printf("Are we there yet?\n")); | |
char buf[256]; | |
ssize_t nread; | |
while ((nread = fread(buf, 1, sizeof(buf)-1, f)) > 0) { | |
buf[nread] = '\0'; | |
printf("%s", buf); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bad syntax with the parentheses. ScopeGuard vestiges visible. Making f_ private is unnecessary - shouldn't be touching the variable anyway. Unnecessary double-statement semantics.