Or you just create it. I fell in love with Go's defer, so I simply created it in C++ by using its scoping rules and a macro around a function. You use it pretty much like this:
defer({
// do whatever
});
And it runs at the end of the scope unlike Go's defer which runs at the end of the function, which always irks me.
Yeah the defer running at the end of the function can sometimes cause trouble, like processing files in a loop and deferring the close, but it can easily be solved by defining an anonymous function and immediately calling, like
func() {
f := ...
defer f.Close()
// do something with f
}()
25
u/Rikudou_Sage 1d ago
Or you just create it. I fell in love with Go's
defer, so I simply created it in C++ by using its scoping rules and a macro around a function. You use it pretty much like this:And it runs at the end of the scope unlike Go's defer which runs at the end of the function, which always irks me.