Hacker News new | ask | show | jobs
by es3n1n 400 days ago
yeah sorry i didnt feel like implementing my own RAII stuff for all the COM thingies due to time constraints. it will be changed in the next update though
4 comments

Honestly if this isn't part of a public API this isn't very cursed in terms of C++, especially if you have a lot of one-off cleanup operations.

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(); };`.

I think the syntax is exactly why they're saying it's cursed. IMO your suggestion is no better - yes it makes defer look like a keyword, but it's not! As I said in a sibling comment, I think it's clearer if you're honest that you're using a macro: 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();});
Sure, I've used __LINE__ for this before too, and yeah I agree that my keyword construction was too clever (seemed cool at the time, since the macro had a dangling = at the end to make it work).
Why did you write it with two structs though? You could do

    #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.