Étant donné une instance de UnsafeMutablePointer
, quel est le point d'appeler deinitialize(count:)
juste avant deallocate(capacity:)
?Swift UnsafeMutablePointer: Dois-je appeler deinitialize avant deallocate?
Vous ne pouvez pas simplement appeler deallocate(capacity:)
?
J'ai vu ce en lisant la section « Utilisation dactylographié Pointeurs » de l'article Unsafe Swift: Using Pointers And Interacting With C sur raywenderlich.com.
L'article contient le code ci-dessous, que vous pouvez ajouter à un nouveau terrain de jeu dans 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)") } }