How to (kind of) emulate RAII using `defer`

I have three separate comments about this…

First, I’m not a big fan of the C++ RAII model because it ties resource management to memory management. I kinda like the way defer work without this:

let f = try open()
defer { close(f) }
… work with `f` …

Everything is nice and visible.

Second, a common idiom in Swift is to provide a withXxx(…) function that calls a closure with the value and cleans up on return. For example:

func withOpenFile<Result>(_ body: (_ f: File) throws -> Result) throws -> Result {
    let f = try open()
    defer { close(f) }
    return body(f)
}

let r = withOpenFile() { f in
    return … read f to generate r …
}

Finally, if you want to go down the RAII path, check out the recent discussions on move-only types. A good place to start is here but there’s been a lot of activity in this space recently.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

5 Likes