Search code examples
swiftunsafe-pointersswift4.1

Swift 4.1 deinitialize and deallocate(capacity:) deprecated


I've been saying this to form a C array of CGPoint:

let arr = UnsafeMutablePointer<CGPoint>.allocate(capacity:4)
defer {
    arr.deinitialize()
    arr.deallocate(capacity:4)
}
arr[0] = CGPoint(x:0,y:0)
arr[1] = CGPoint(x:50,y:50)
arr[2] = CGPoint(x:50,y:50)
arr[3] = CGPoint(x:0,y:100)

Now (Swift 4.1 in the Xcode 9.3 beta) both deinitialize and deallocate(capacity:) are deprecated. It looks like what I'm supposed to say now might be:

defer {
    arr.deinitialize(count:4)
    arr.deallocate()
}

Is that right?


Solution

  • Yes, that is part of SE-0184 Unsafe[Mutable][Raw][Buffer]Pointer: add missing methods, adjust existing labels for clarity, and remove deallocation size, which has been implemented in Swift 4.1.

    In particular:

    Removing capacity from deallocate(capacity:) will end the confusion over what deallocate() does, making it obvious that deallocate() will free the entire memory block at self, just as if free() were called on it.

    The old deallocate(capacity:) method should be marked as deprecated and eventually removed since it currently encourages dangerously incorrect code.