[swift-evolution] [Proposal] Scoped resources (like C# using statement)
Kevin Ballard
kevin at sb.org
Thu Dec 31 18:26:15 CST 2015
On Thu, Dec 31, 2015, at 01:40 PM, Michel Fortin wrote:
> Le 30 déc. 2015 à 16:40, Kevin Ballard via swift-evolution <swift-evolution at swift.org> a écrit :
> > On Wed, Dec 30, 2015, at 01:33 PM, Joe Groff wrote:
> >> Another possibility I've thought of is defining `defer { val }` to guarantee that val remains alive until the defer fires on scope exit. That might let us leave `defer` as the one "guarantee something happens exactly at scope exit" language construct.
> >
> > Oh that's cute. I'd probably want to say `defer { _ = val }` though, to make it obvious that this is intentional.
>
> Or you could make it even more obvious what this is by giving that feature a name. For instance:
>
> defer { _fixLifetime(val) }
>
> The good thing about this one is that it already works, because that's what `withExtendedLifetime` does internally. Also, if you search a bit, you'll end up here with a nice explanation of what that function does.
> https://github.com/apple/swift/blob/8d9ef80304d7b36e13619ea50e6e76f3ec9221ba/stdlib/public/core/LifetimeManager.swift#L45
>
> So why not simply remove the underscore?
Because it's not a very good API? Having some magic function called `fixLifetime()` that keeps values alive is a little weird. `withExtendedLifetime()` is also slightly weird, but it makes more sense than fixLifetime() does, since withExtendedLifetime() is the specific solution to the problem of "I need to ensure this value remains alive for this entire scope because reasons".
I'd much rather just see the syntax `_ = val` be converted into `Builtin.fixLifetime(val)` because the only reason to write an expression like that is because you want to make sure the value is still alive at that point (that and because it's not unreasonable for people to assume that `_ = val` will keep the value alive, so it would be nice to make that assumption actually be correct).
-Kevin Ballard
More information about the swift-evolution
mailing list