[swift-users] unsafe memory model questions

Ray Fix rayfix at gmail.com
Sun Dec 11 16:51:50 CST 2016


So bindMemory is part of the memory model and memory can only bind to one type at a time to avoid aliasing. But what does binding actually do? Is it somehow communicating with the optimizer?

A tangentially related second question, in the following example:

  let count = 3
  let mutablePointer = UnsafeMutablePointer<Int16>.allocate(capacity: count)
  defer {
    mutablePointer.deallocate(capacity: count)

  mutablePointer.initialize(to: 1234, count: count)
  defer {
    mutablePointer.deinitialize(count: count)  // must I do this?

Is it bad form if I don’t deinitialize and go straight to deallocate?  I can see where it is important for ref types (to update ref counts, etc).  Is it one of those things that the optimizer can remove for the case of value types?

Finally, if I initalize with some other means, such as with a raw buffer pointer subscript, is there any need to deinitialize?  Can such memory be considered initialized if I bind it with a type?

  // 1
  let pointer = malloc(byteCount)
  defer {

  let mutableRawBufferPointer = UnsafeMutableRawBufferPointer(start: pointer, count: byteCount)
  for index in mutableRawBufferPointer.indices {
    mutableRawBufferPointer[index] = 42 + UInt8(index)

Perhaps there is a document or proposal somewhere that talks about these things. Sorry if I missed it.

Thanks as always,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161211/0b33573d/attachment.html>

More information about the swift-users mailing list