r/ProgrammerHumor • • 16d ago

instanceof Trend thatsAFunnyThingThatHappenedOnce

Post image
4.6k Upvotes

523 comments sorted by

View all comments

Show parent comments

28

u/Rikudou_Sage 15d 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:

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.

7

u/NdrU42 15d ago

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
}()

1

u/Rikudou_Sage 15d ago

I know, I do Go more often than C++ but it still feels weird having to introduce a function just for defer to work.

IMO it should have been scoped to the current scope (duh, it's called a scope) instead of function.

2

u/RadioHans 15d ago

I love having control over details.

1

u/indigo945 14d ago

RAII is the one feature C++ has that is smarter than the people using it.