| > I can't parse this super well on mobile, but what invariant is this maintaining. The stack length (and contents, too). It pushes, but ensures a pop occurs upon returning. So the stack looks the same before and after. > I was imagining a function that manipulated a collection, and e.g. needed to decrement a length field to ensure the observable elements remained valid, then increment it, then do something else. That is exactly what the code is doing. > EDIT: oh, I think I see; is your code validating the invariant, or maintaining it? Both. First it manipulates the stack (pushing onto it), then it does some stuff. Then before returning, it validates that the last element is still the one pushed, then pops that element, returning the stack to its original length & state. > The gnarliest scenario I recall was a ring-buffer implementation that [...] That sounds like the kind of thing scope guards would be good at. |
E.g. in the case you provided, if pop & push couldn't fail, that would just be two calls in sequence.