Skip to content

Instantly share code, notes, and snippets.

@skaslev
Last active October 15, 2021 23:18
Show Gist options
  • Save skaslev/4b6dd4166e5cc88a6721 to your computer and use it in GitHub Desktop.
Save skaslev/4b6dd4166e5cc88a6721 to your computer and use it in GitHub Desktop.
Go-like defer statement for C++
#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;
}
@Nameguy
Copy link

Nameguy commented May 3, 2016

Bad syntax with the parentheses. ScopeGuard vestiges visible. Making f_ private is unnecessary - shouldn't be touching the variable anyway. Unnecessary double-statement semantics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment