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

Kevin Ballard kevin at sb.org
Wed Dec 16 01:51:50 CST 2015


On Tue, Dec 15, 2015, at 11:25 PM, Dave Abrahams wrote:
> 
> > On Dec 15, 2015, at 6:46 PM, Kevin Ballard <kevin at sb.org> wrote:
> > 
> > On Tue, Dec 15, 2015, at 06:39 PM, Dave Abrahams 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?
> > 
> > I'm thinking here of cases like passing a context pointer to KVO. You're not actually mutating it, you just need a pointer that's the same every time you call the code.
> 
> Well, it is not possible to code a version of withUnsafePointer that makes that guarantee in Swift.

Yeah but we want to move in the direction of making that more reliable, not less. I forget who but someone said in another thread that global variables can be reliably passed by-ref to functions that take pointers already (even though the Swift documentation does not guarantee this).

Come to think of it, what's the actual use-case for withUnsafePointer()? If a value is mutable, you can already use &x or withUnsafeMutablePointer(), and if it's immutable, you can't call withUnsafePointer() today anyway. The proposed change would just make withUnsafePointer() into the equivalent of `var x = value; callSomethingWith(&x)`. The only reason to really want a withUnsafePointer() function is if it can give you an UnsafePointer to an immutable value without copying it, but we can't do that. I'm inclined to say we should just get rid of withUnsafePointer() entirely, at least until such time as Swift has a way to pass immutable values by-ref.

-Kevin Ballard


More information about the swift-dev mailing list