鉴于UnsafeMutablePointer
的实例,在deinitialize(count:)
之前调用deallocate(capacity:)
的重点是什么?
你只能打电话给deallocate(capacity:)
吗?
我在阅读“#34;使用键入的指针"关于Unsafe Swift: Using Pointers And Interacting With C的文章raywenderlich.com。
该文章包含以下代码,您可以将其添加到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)") } }
答案 0 :(得分:1)
如果你继续阅读,文章将在下面解释代码。
更新:如下面评论中的用户atrick所述,只有非平凡类型才需要取消初始化。也就是说,包括去初始化是一种很好的方式来证明你的代码,以防你改变一些非平凡的东西。此外,它通常不会花费任何费用,因为编译器会优化它。