A DisposableStack
is not exactly a "stack" in terms of its interface. It has several methods for pushing disposers to it, but it has no way to pop one disposer off. Rather, all disposers are popped and executed one-by-one when the stack is disposed.
You register disposable resources to the DisposableStack
using its use()
, adopt()
, or defer()
methods.
using disposer = new DisposableStack();
const reader = disposer.use(stream.getReader());
Then, when the disposer
goes out of scope, all resources registered to it are disposed in reverse order of registration, unless they have been moved out with move()
.
It is good practice to not extract the resource acquisition expression to a separate statement, no matter how long the expression is. You should always wrap the use()
or adopt()
call around the resource acquisition expression to ensure that the resource is registered to the stack immediately.
using disposer = new DisposableStack();
const reader = stream.getReader();
disposer.use(reader);
Functionally, these two code snippets are equivalent. However, the first one is less error-prone because the resource is declared and registered in a single line. If someone puts more code between the second and third lines of the second snippet, an error could occur, causing the resource to leak.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4