【问题标题】:Swift UnsafeMutablePointer: Must I call deinitialize before deallocate?Swift UnsafeMutablePointer:我必须在释放之前调用 deinitialize 吗?
【发布时间】:2017-10-18 16:00:18
【问题描述】:

给定一个UnsafeMutablePointer 的实例,在deallocate(capacity:) 之前调用deinitialize(count:) 有什么意义?

你不能打电话给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)")
  }
}

【问题讨论】:

    标签: swift memory-management unsafemutablepointer


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多