Given an instance of UnsafeMutablePointer
, what's the point of calling deinitialize(count:)
right before deallocate(capacity:)
?
Can't you just call deallocate(capacity:)
?
I saw this when reading the section "Using Typed Pointers" of the article Unsafe Swift: Using Pointers And Interacting With C on raywenderlich.com.
The article contains the code below, which you can add to a new playground in Xcode.
let count = 2 let stride = MemoryLayout<Int>.stride let alignment = MemoryLayout<Int>.alignment let byteCount = stride * count do { print("Typed pointers") let pointer = UnsafeMutablePointer<Int>.allocate(capacity: count) pointer.initialize(to: 0, count: count) defer { pointer.deinitialize(count: count) pointer.deallocate(capacity: count) } pointer.pointee = 42 pointer.advanced(by: 1).pointee = 6 pointer.pointee pointer.advanced(by: 1).pointee let bufferPointer = UnsafeBufferPointer(start: pointer, count: count) for (index, value) in bufferPointer.enumerated() { print("value \(index): \(value)") } }