monotonic_buffer_resource and exception handling

90 Views Asked by At

The monotonic_buffer_resource works a bit like a stack that only supports push but not pop. Unfortunately I see no way howto revert to its previous state when catching an exception.

Even when handing your errors manually in the absence of exception handling, then you may still need to rollback your data to a previous state. How can you capture the state of this allocator resource and later revert to that state? If not possible, is there another resource I can use instead? Maybe a non standard one?

Otherwise, do I miss a reason why the monotonic_buffer_resource lacks any means to revert to a previous state? This should be exceptionally simple in my view, because this allocation resource skips calls to destructors anyhow.

1

There are 1 best solutions below

5
Nicol Bolas On

While this allocator is a "stack allocator", that does not mean the allocations it produces have a lifetime that is in any way bound by the actual execution stack of a thread. That is, just because you unwind the stack to some point does not mean that all allocations that were made within the now terminated part of the execution stack are now defunct.

You could have used those allocations as part of some object that now resides in some other object that survived the unwinding. You don't know; you cannot know because the allocator does not keep track of individual allocations. Indeed, not keeping track of individual allocations is the entire point.

Because the execution stack and the allocation stack are entirely separate, it is very dangerous to assume anything about the relationship between the two. If you are rigorous about how you use your monotonic allocations, then you might be able to do something like what you're talking about. But since there is no requirement that you do this (and it's very, very easy to get wrong), there's really no point.

Furthermore, it just violates the designed intent of the class. Again, the whole point is that it doesn't track individual allocations. You allocate a bunch of things, and then you throw them all away at the same time. That's the usage pattern. If your usage pattern is to allocate a bunch of things, throw some set of them away, then allocate more, then throw all of them away, that's a different usage pattern.

Or you just have two of them.