[swift-evolution] [Draft] UnsafeRawPointer API

Andrew Trick atrick at apple.com
Wed Jun 29 20:19:11 CDT 2016


> On Jun 27, 2016, at 4:53 PM, Andrew Trick <atrick at apple.com> wrote:
> 
> 
>> On Jun 23, 2016, at 6:40 PM, Andrew Trick via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> https://github.com/atrick/swift-evolution/blob/voidpointer/proposals/XXXX-unsaferawpointer.md
> 
> Would anyone like to bikeshed the allocation API? Here are two options with a slight stylistic difference:
> 
> # Option 1:
> 
> extension UnsafeMutableRawPointer {
>    init<T>(allocatingCapacity: Int, of: T.Type)
> 
>    func deallocate<T>(capacity: Int, of: T.Type)
> }
> 
> let ptrToA = UnsafeMutableRawPointer(allocatingCapacity: 1, of: A.self)
>  .initialize(A.self, with: A())
> ptrToA.deinitialize(count: 1).deallocate(capacity: 1, of: A.self)
> 
> # Option 2:
> 
> extension UnsafeMutableRawPointer {
>    static allocate<T>(capacity: Int, of: T.Type) -> UnsafeMutableRawPointer
> 
>    func deallocate<T>(capacity: Int, of: T.Type)
> }
> 
> let ptrToA = UnsafeMutableRawPointer.allocate(capacity: 1, of: A.self)
>  .initialize(A.self, with: A())
> ptrToA.deinitialize(count: 1).deallocate(capacity: 1, of: A.self)

Since no one else has weighed in, and DaveA and I are in violent agreement, I'm going to revise the proposal to change the allocation API from:

  let rawPtr = UnsafeRawPointer(allocatingCapacity: n, of: T.self)

to

  let rawPtr = UnsafeRawPointer.allocate(capacity: n, of: T.self)

The only reason I had proposed the former was to mimic the current
UnsafePointer API. However, an initializer's primary purpose should be to
construct an instance. This functions primary purpose is to allocate
memory, returning an new instance as a useful side effect. This also
provides natural symmetry with:

  rawPtr.deallocate(capacity: n, of: T.self)

-Andy


More information about the swift-evolution mailing list