寻址的内存UnsafeMutablePointer
可以处于以下三种状态之一:
/// - Memory is not allocated (for example, pointer is null, or memory has
/// been deallocated previously).
///
/// - Memory is allocated, but value has not been initialized.
///
/// - Memory is allocated and value is initialised.
通话
let memory = UnsafeMutablePointer<Character>(allocatingCapacity: count)
分配内存,但不初始化:
/// Allocate and point at uninitialized aligned memory for `count`
/// instances of `Pointee`.
///
/// - Postcondition: The pointee is allocated, but not initialized.
public init(allocatingCapacity count: Int)
另一方面,下标方法要求指针被初始化:
/// Access the pointee at `self + i`.
///
/// - Precondition: the pointee at `self + i` is initialized.
public subscript(i: Int) -> Pointee { get nonmutating set }
结果,您的代码在_swift_release_
.
要从(字符)数组初始化分配的内存,可以使用
memory.initializeFrom(array)
当然,您最终必须取消初始化并取消分配内存。
另一种方法是
var cArray: [Character] = ["A", "B", "C"]
cArray.withUnsafeMutableBufferPointer { bufPtr in
// ...
}
这里没有分配新的内存,但是使用指向数组连续存储的指针调用闭包。此缓冲区指针仅在闭包内有效。