给定一个实例,在此之前UnsafeMutablePointer
调用有什么意义?deinitialize(count:)
deallocate(capacity:)
你不能打电话deallocate(capacity:)
吗?
我在阅读raywenderlich.com上的文章Unsafe Swift: Using Pointers And Interacting With C的“使用类型指针”部分时看到了这一点。
本文包含以下代码,您可以将其添加到 Xcode 中的新 Playground 中。
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)") } }