3 ms·
That one executes deferred statements at end of scope, instead of on function exit. That doesn't work well if your defer-statement occurs in an if-body, for exa
by sltkr 6y ago
That one executes deferred statements at end of scope, instead of on function exit. That doesn't work well if your defer-statement occurs in an if-body, for example.
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.