Swift 里的指针

基础知识

指针的内存状态

typed? initiated?

之前分配的内存可能被释放,使得指针指向了未被分配的内存。
有两种方式可以使得指针指向的内存处于Uninitialized状态:

  1. 刚刚被分配内存
  2. 内存被deinitialized
var bytes: [UInt8] = [39, 77, 111, 111, 102, 33, 39, 0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)

此时,uint8Pointer处于Uninitialized状态。

已经被初始化的内存,可以通过pointee属性或者下标方式访问。

let ptr: UnsafePointer<Int> = ...
// ptr.pointee == 23
// ptr[0] == 23

Typed Pointers

指向内存能否改动 可否进行边界检查
UnsafePointer
UnsafeMutablePointer
UnsafeBufferPointer
UnsafeMutableBufferPointer

Raw Pointers

即指向的内存没有特定类型。

Use raw pointers and buffers to access memory for loading and storing as raw bytes.

  • automated memory management ❌
  • type safety ❌
  • alignment guarantees ❌

指针类型转换

前提条件

Memory that has been bound to a type can be rebound to a different type only after it has been deinitialized or if the bound type is a trivial type

  • 内存已经被 deinitialized
  • 内存指向的类型是 trivial 的

deinitialized 的地址,有三种出路:

  1. 以相同类型被 reinitialized
  2. bound to a new type
  3. deallocated

typed pointer 状态转换

untrivial pointee

trivial pointee

相比之下,pointee 类型是 trivial 的,可以进行更多的操作。

猜你喜欢

转载自www.cnblogs.com/huahuahu/p/Swift-li-de-zhi-zhen.html