[swift-evolution] Proposal: [stdlib] Remove withUnsafe[Mutable]Pointer[s]()
Dave Abrahams
dabrahams at apple.com
Wed Dec 16 14:22:13 CST 2015
> On Dec 16, 2015, at 11:54 AM, Michael Gottesman via swift-evolution <swift-evolution at swift.org> wrote:
>
>>
>> On Dec 16, 2015, at 1:49 PM, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> Another replacement for withUnsafe[Mutable]Pointer is declaring a nested function of the appropriate type (this is equivalent to the anonymous closure, but perhaps more readable):
>>
>> func foo(ptr: UnsafePointer<Int>) {
>> // ...
>> }
>> foo(&x)
>>
>> -Kevin
>>
>> On Wed, Dec 16, 2015, at 11:38 AM, Kevin Ballard wrote:
>>> # Introduction
>>>
>>> The stdlib provides functions withUnsafePointer() and withUnsafeMutablePointer() (and plural variants) that take an inout reference and call a block with the UnsafePointer/UnsafeMutablePointer created from the reference.
>>>
>>> # Problem
>>>
>>> withUnsafePointer() can only be used with mutable variables, because those are the only things that can be used with inout &refs. Both functions are also fairly useless, as &x refs can be passed directly to functions taking an UnsafePointer or UnsafeMutablePointer. The existence of the functions mostly just causes people to think they're necessary when they're not. The provide no functionality that passing &x refs directly to the functions taking a pointer doesn't already fulfill.
>>>
>>> # Solution
>>>
>>> Remove the functions from the stdlib. The Swift Book should also be updated to talk about passing an &x ref to a function that takes an UnsafePointer or UnsafeMutablePointer (but of course changes to the book are not covered by the open-source project). Most uses of these functions can probably be replaced with a &x ref directly. If any can't, they could be replaced with the following equivalent expressions:
>>>
>>> { (ptr: UnsafePointer<Int>) in
>>> // ...
>>> }(&x)
>>>
>>> or:
>>>
>>> withExtendedLifetime(&x) { (ptr: UnsafePointer<Int>) in
>>> // ...
>>> }
>
> One thing to keep in mind here is that with*Pointer and friends is also meant to enable one to work around issues with the optimizer if they come up in a convenient manner. I.e. imagine if one is attempting to process an image using a 5d array and for whatever reason, you are not getting the performance you need. Hopefully you would file a bug report and then use with*Pointer for your image processing loop.
>
> My fear about withExtendedLifetime is that the name is a misnomer. You are not extending the lifetime.
What makes you say that?
If in fact it is true, shouldn't you file a bug report?
-Dave
More information about the swift-evolution
mailing list