5

给定一个实例,在此之前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)")
  }
}
4

1 回答 1

2

如果您继续阅读,本文将在代码下方进行解释。

更新:正如用户 atrick 在下面的评论中所指出的,只有非平凡类型才需要取消初始化。也就是说,包括取消初始化是将来证明您的代码的好方法,以防您更改为不重要的东西。此外,它通常不会花费任何成本,因为编译器会对其进行优化。

于 2017-10-18T16:03:58.247 回答