为什么下面的代码要求我手动使用unsafe_pointer.deinitialize(count: 1)
来取消初始化实例?
如果我只使用unsafe_pointer.deallocate()
,该实例在我的内存中仍然存在。那么使用deallocate()
的目的是什么?
提前抱歉,因为我是第一次尝试学习 MRC。
class Unsafe_Memory {
var name = "Hello World"
deinit {
print("\(type(of: self)) is deinited and deallocated")
}
}
let unsafe_pointer: UnsafeMutablePointer<Unsafe_Memory> = .allocate(capacity: 1)
unsafe_pointer.pointee = Unsafe_Memory()
dump(unsafe_pointer.pointee)
unsafe_pointer.pointee.name = "Changed"
dump(unsafe_pointer.pointee)
unsafe_pointer.deinitialize(count: 1)
unsafe_pointer.deallocate()
最佳答案
您必须对任何重要类型调用deinitialize
。根据Apple Docs ,
A trivial type can be copied bit for bit with no indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references or other forms of indirection are trivial, as are imported C structs and enums. Copying memory that contains values of nontrivial types can only be done safely with a typed pointer. Copying bytes directly from nontrivial, in-memory values does not produce valid copies and can only be done by calling a C API, such as memmove().
调用deinitialize
首先会取消初始化该内存,但如 docs状态,“调用deinitialize(count:)
后,内存未初始化,但仍绑定(bind)到 Pointee 类型”。
之后,您可以通过调用 deallocate()
释放该内存块,类似于 C 中的 free()
。deallocate()
只能在非平凡类型或未初始化的内存块上调用。
如果类型很简单,则不必调用deinitialize
。无论如何,最好调用 deinitialize
以防万一您的类型将来变得不平凡,并且调用它不会花费您任何费用。
您可以尝试运行代码而不调用deallocate
。 deinit
block 仍将被执行,因为 deinitialize
将运行该 block 。但是,该内存块仍然被占用并且不会被释放,直到您调用deallocate
。
关于swift - deinitialize() 与 deallocate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74990221/