[swift-users] Is '_ = x' guaranteed to hold a reference to x?

Taylor Swift kelvin13ma at gmail.com
Fri Jun 30 15:08:25 CDT 2017


You should probably use `withExtendedLifetime(_:_:)
<https://developer.apple.com/documentation/swift/1541033-withextendedlifetime>`
for this.

On Fri, Jun 30, 2017 at 2:54 PM, Charles Srstka via swift-users <
swift-users at swift.org> wrote:

> > On Jun 30, 2017, at 1:47 PM, Mike Ferenduros via swift-users <
> swift-users at swift.org> wrote:
> >
> > I'm doing a RAII sort of thing with an object, and would like to keep it
> alive until an completion-block is called (asynchronously).
> >
> > Is it sufficient to say '_ = x' in the completion-block to keep a live
> reference to the object?
> >
> > I was told that the optimiser is free to discard this line, and thus the
> object could be freed prematurely depending on how the code is compiled. If
> so, is there an idiomatic way to do this? Or should I just avoid RAII in
> Swift?
>
> Nope. In fact, if you try this, you’ll find that it dies immediately after
> the initializer returns:
>
> class C {
>         deinit { print("Deinit!") }
> }
>
> do {
>         print("Creating")
>         _ = C()
>         print("Created")
> }
> print("Left the block”)
>
> - - - - -
>
> Creating
> Deinit!
> Created
> Left the block
>
> Charles
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170630/ca4fe7c5/attachment.html>


More information about the swift-users mailing list