Go's defer function is very predictable, not so much because Go's defer is magic but precisely because it isn't. There aren't a ton of features for it to interact with.
This also isn't a special virtue of Go; IMHO it's a special (not unique, but unusual) failing of C++. It was insanely complicated already in the 90s and every standard since then has only made it worse.
I don't think it's super valuable to mimic the Go syntax anyway. In C++ you can fairly easily implement a class that works like this, which is fairly clean and intuitive:
void func() {
Deferred deferred;
for (int i = 0; i < 10; ++i) {
deferred.push([] { some callback });
}
// when Deferred is destroyed, it executes callbacks.
}
This is somewhat more powerful than Go's defer in that it gives the user explicit control over the scope. I think in Go you'd have to create a closure and call it immediately to create a nested scope for the purposes of executing deferred statements early.Granted, both BOOST_SCOPE_EXIT and your defer macro work at block end, not function end, but I agree with OP that this is practically always the better approach, so I don't think we should look at this thing as C++ trying to copy go features with lousy hacks. It's probably the other way around, if anything. And modern implentations in C++ (like yours) are extremely straightforward.
the downside is having to write nullptr instead of just the closure. Something like this really should be part of the standard.