Swift 里的指针

基础知识
指针的内存状态
typed? | initiated? |
---|---|
❌ | ❌ |
✅ | ❌ |
✅ | ✅ |
之前分配的内存可能被释放,使得指针指向了未被分配的内存。
有两种方式可以使得指针指向的内存处于Uninitialized
状态:
- 刚刚被分配内存
- 内存被
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
的地址,有三种出路:
- 以相同类型被 reinitialized
- bound to a new type
- deallocated
typed pointer 状态转换
untrivial pointee

trivial pointee

相比之下,pointee 类型是 trivial 的,可以进行更多的操作。
下起雨,也要勇敢前行