Swift UnsafeMutablePointer: Must I call deinitialize before deallocate?
Asked Answered
H

1

5

Given an instance of UnsafeMutablePointer, what's the point of calling deinitialize(count:) right before deallocate(capacity:)?

Can't you just call deallocate(capacity:)?


I saw this when reading the section "Using Typed Pointers" of the article Unsafe Swift: Using Pointers And Interacting With C on raywenderlich.com.

The article contains the code below, which you can add to a new playground in 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)")
  }
}
Heredia answered 18/10, 2017 at 16:0 Comment(0)
H
3

The article explains below the code, if you keep reading.

Update: as noted by user atrick in the comments below, deinitialization is only required for non-trivial types. That said, including deinitialization is a good way to future proof your code in case you change to something non-trivial. Also, it usually doesn’t cost anything since the compiler will optimize it out.

Heredia answered 18/10, 2017 at 16:3 Comment(1)
What happens if I call deinitialize after deallocate?Kinata

© 2022 - 2024 — McMap. All rights reserved.