Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UnsafeMutablePointer: Must I call deinitialize before deallocate?

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)")
  }
}
like image 578
ma11hew28 Avatar asked Oct 30 '22 00:10

ma11hew28


1 Answers

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.

like image 128
ma11hew28 Avatar answered Nov 15 '22 06:11

ma11hew28