logoalt Hacker News

mort96yesterday at 9:25 AM2 repliesview on HN

C++ implementations of defer are either really ugly thanks to using lambdas and explicitly named variables which only exist to have scoped object, or they depend on macros which need to have either a long manually namespaced name or you risk stepping on the toes of a library. I had to rename my defer macro from DEFER to MYPOROGRAM_DEFER in a project due to a macro collision.

C++ would be a nicer language with native defer. Working directly with C APIs (which is one of the main reasons to use C++ over Rust or Zig these days) would greatly benefit from it.


Replies

pjmlpyesterday at 9:40 AM

Because they are all the consequence of holding it wrong, avoiding RAII solutions.

Working with native C APIs in C++ is akin to using unsafe in Rust, C#, Swift..., it should be wrapped in type safe functions or classes/structs, never used directly outside implementation code.

If folks actually followed this more often, there would be so much less CVE reports in C++ code caused by calling into C.

show 2 replies
leni536yesterday at 10:07 AM

Not to mention that the `scope_success` and `scope_failure` variants have to use `std::uncaught_exceptions()`, which is hostile to codegen and also has other problems, especially in coroutines. C++ could get exception-aware variants of language defer.

show 1 reply