swift - deinitialize() 与 deallocate()

标签 swift pointers memory-management automatic-ref-counting

为什么下面的代码要求我手动使用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 以防万一您的类型将来变得不平凡,并且调用它不会花费您任何费用。

您可以尝试运行代码而不调用deallocatedeinit block 仍将被执行,因为 deinitialize 将运行该 block 。但是,该内存块仍然被占用并且不会被释放,直到您调用deallocate

关于swift - deinitialize() 与 deallocate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74990221/

相关文章:

swift - 无法从 UITableViewCell 显示 View Controller

c - 包含指向其他结构的指针的堆栈

c - 重新分配字符串文字

memory-management - 生命周期不够长使用rust

c++ - 具有动态分配成员的动态创建对象的访问成本

c - 如何将位图中的位映射到伙伴分配器中的物理页?

ios - Storyboard 状态栏后面的内容

ios - 如何测试包含应用程序是否授予 "Allow Full Access"权限?

ios - 如何在 didSelectRowAtIndexPath 中触发选定 Nib 单元格的某些转场

c - 如何在循环中实例化新的结构实例