by es3n1n · 1y ago · 0 comments
scope_exit{[&]{ ... } };I think the only bit I don't like personally is the syntax. I normally implement defer as a macro to keep things clean. If done correctly it can look like a keyword: `defer []{ something(); };`.
Or you could even make a non-macro version (but then you need to think of variable names for each defer):
auto defer_uninitialise = do_defer([](){CoUninitialize();}); #define defer(body) DeferHolder COMMON_CAT(_defer_instance, __LINE__) {([&]()->void body)};
and call it as defer({
function body here;
});
Which looks much nicer. The preprocessor treats balanced curlies as one single token regardless of how many lines it spans, precisely to enable this usage.