[swift-dev] `withUnsafePointer` mutates `self`

Joe Groff jgroff at apple.com
Wed Dec 16 13:39:34 CST 2015


> On Dec 15, 2015, at 6:39 PM, Dave Abrahams via swift-dev <swift-dev at swift.org> wrote:
> 
> 
>> On Dec 15, 2015, at 6:33 PM, Kevin Ballard via swift-dev <swift-dev at swift.org> wrote:
>> 
>> On Tue, Dec 15, 2015, at 03:03 PM, Joe Groff via swift-dev wrote:
>>> 
>>> Yeah, it seems to me like a reasonable refinement for 'withUnsafePointer' to take an immutable parameter. Since this is a stdlib API change, you should suggest that on swift-evolution.
>> 
>> A change like that is going to break any code that relies on the inout optimization (where it uses call-by-reference instead of copy-in copy-out when possible). Yes, such code is in violation of Swift semantics today, but it does work.
> 
> Two questions:
> 
> 1. Don’t we want a withUnsafeMutablePointer for the mutating cases (where the inout optimization can take effect) anyway?

Yeah, a withUnsafeMutablePointer variant that is inout would be necessary.

> 2. Joe, these APIs predate many of your changes that make &x transparently convert to Unsafe[Mutable]Pointer arguments.  Are they obsolete?  Can we replace them with { x: Unsafe[Mutable]Pointer in … }(&y) ?

Not if you need the same pointer across multiple calls, or you need to convert or adjust the pointer before the call. A call like foo(&x) that involves a pointer conversion only guarantees that pointer for that exact call, as if you'd written withUnsafe[Mutable]Pointer(&x) { foo($0) }. 

-Joe


More information about the swift-dev mailing list