有关UnsafeMutablePointer的destroy()的术语

/// Destroy the object the pointer points to. /// /// Precondition: the memory is initialized. /// /// Postcondition: the value has been destroyed and the memory must /// be initialized before being used again. func destroy() 

在这种情况下,术语objectmemoryvalue是什么意思?

当你自己pipe理内存而不是让语言运行库为你处理内存的低级编程时,使用内存是一个两阶段的过程。

首先,你分配一个内存区域。 这只是保留了一些原始空间,它没有设置内存有任何特定的值。 内存可能包含随机垃圾,也可能包含以前在内存中的某些数据。 你不应该依赖这个具有任何特殊价值的内存区域。

然后,通过将该内存区域设置为一个明确定义的值来初始化它。 也许你把它设置为全零。 也许你把它分成块,把这些块作为单独的variables保存在内存中。 也许你从其他地方复制一些数据。

如果您使用的是像Swift这样的高级语言,您可能需要设置内存来表示一个对象 – 一组成员variables和其他支持数据。 这个数据集合是以一种非常特定的方式构造的,所以你可以把它作为一个特定的对象types传递给其他函数,并调用它的成员方法。 要设置对象,你可以把它叫做“init”方法来适当地设置成员variables。

这里,将内存设置为“有价值”并在内存中创build“对象”是类似的概念,但术语“对象”意味着操作在更高的抽象层次。

当你完成了你的目标,你反过来通过相同的步骤。 首先,您可以执行调用对象的取消初始化代码的“高级”操作。 例如,调用类的deinit()方法,或释放对其他对象的引用。

在这一点上,内存仍然是分配给你的,但现在又回到了被视为“垃圾”的地步,你一定不要看。 但是,您仍然需要“释放”内存(退回)以返回到您开始的状态。 或者,您可以select不使用,而是重新使用原始内存并就地创build一个新对象。

UnsafeMutablePointer可以帮助你完成这个过程,分配和释放内存很容易,但更重要的是,可以帮助你安全地在内存中创build对象,并且有很多帮助方法来移动内存的控制,从不同types的源数据等

这是一个例子:

 class MyClass { init() { println("created") } deinit { println("destroyed") } } struct MyStruct { let i: Int let d: Double let c: MyClass } // allocate enough memory for 1 MyStruct object // (you can also allocate enough memory for several objects) var aStruct = UnsafeMutablePointer<MyStruct>.alloc(1) // no MyStruct has been created yet – we've just allocated // enough memory to hold one // set that memory to represent a new MyStruct object aStruct.initialize(MyStruct(i: 4, d: 2.2, c: MyClass())) println("Memory contains a MyStruct with i = \(aStruct.memory.i)") // should see the class print "destroyed" aStruct.destroy() // at this point, "memory" should be conisidered rubbish // reinitialize it with something new: aStruct.initialize(MyStruct(i: 8, d: 3.3, c: MyClass())) println("Memory contains a MyStruct with i = \(aStruct.memory.i)") // should see the class print "destroyed" aStruct.destroy() // finally, deallocate the raw memory aStruct.dealloc(1) 

很明显,像UnsafeMutablePointer这样的UnsafeMutablePointer ,如果你不知道自己在做什么,使用它仍然是危险的。 但是,如果没有这种帮助,直接访问内存仍然比安全更安全。