[swift-evolution] [Pitch] Don't require & for UnsafeRawPointer
Charles Srstka
cocoadev at charlessoft.com
Wed May 17 15:11:06 CDT 2017
Reading over this again, the proposal should also mention changing withUnsafePointer(to:_:) to no longer take an inout as its first argument.
Charles
> On Apr 20, 2017, at 2:10 PM, Anders Kierulf via swift-evolution <swift-evolution at swift.org> wrote:
>
> Summary: Currently, only mutable values can be passed to UnsafeRawPointer, except for a special case for arrays. That special case should be generalized, allowing any values to be passed to UnsafeRawPointer without using &.
>
> The following code shows the inconsistency in passing values to UnsafeRawPointer:
>
> var varArray = [Int](repeating: 0, count: 6)
> var varTuple = (0, 0, 0, 0, 0, 0)
>
> let letArray = [Int](repeating: 0, count: 6)
> let letTuple = (0, 0, 0, 0, 0, 0)
>
> func get(_ pointer: UnsafeRawPointer, at index: Int) -> Int {
> let a = pointer.bindMemory(to: Int.self, capacity: 6)
> return a[index]
> }
>
> // Array can be passed directly, automatically takes address.
> _ = get(varArray, at: 2) // okay
> _ = get(letArray, at: 2) // okay
>
> // When explicitly taking address, can only pass mutable variables.
> _ = get(&varArray, at: 2) // okay, but seems inconsistent
> _ = get(&letArray, at: 2) // fails: & not allowed
>
> // Passing tuple instead of array fails.
> _ = get(varTuple, at: 2) // fails: wrong type
> _ = get(letTuple, at: 2) // fails: wrong type
>
> // Adding & to pass a tuple only works for mutable values. Having to
> // pass the address using & means that any methods calling this must
> // be mutating, even though they don't mutate.
> _ = get(&varTuple, at: 2) // okay, but forces mutating
> _ = get(&letTuple, at: 2) // fails: cannot pass immutable value
>
> Passing a value to an UnsafeRawPointer parameter should not require use of &, as that forces all code calling it to be mutating. Having a special case for array also doesn't make sense, as the idea of UnsafeRawPointer is that we're interpreting that memory content as whatever we want. Logged as SR-4649.
>
> Proposal:
> - Never require & when passing value to UnsafeRawPointer.
> - Always require & when passing value to UnsafeMutableRawPointer.
>
> (Fixed size arrays are still needed, but with this tweak, workarounds can be made to work.)
>
> Anders Kierulf
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list