gpt4 book ai didi

swift - 从 `self` 走私 `deinit`

转载 作者:行者123 更新时间:2023-12-04 16:03:38 27 4
gpt4 key购买 nike

如果我走私会怎样self出我的 deinit ,通过将其分配给某个外部强引用?下面的这段代码显然格式不正确:

class C: CustomStringConvertible {
let s = "abc"

var description: String {
return "C(id: \(ObjectIdentifier(self)), s: \(s))"
}

deinit {
print("deinit")
globalObject = self
}
}

var globalObject: C!

do {
let localObject = C()
print("localObject: \(localObject)")
print("end of `do`")
}

print("globalObject: \(globalObject!)")

您不能仅仅从 deinit 的中间“改变主意”来取消对象的初始化。 .但有趣的是,这段代码是不确定的,它有时会成功完成,打印:
localObject: C(id: ObjectIdentifier(0x00007f9063f00960), s: abc)
end of `do`
deinit
globalObject: C(id: ObjectIdentifier(0x00007f9063f00960), s: abc)

我正在使用 Code Runner 运行它,它只是使用 swiftc 运行单个文件 Swift 脚本。 .所以这里没有意外的 Playground 拥有的引用。

非确定性从何而来?

最佳答案

这不是答案,但评论太长了:
有趣的是,我只是附加了:

for _ in 1...1000000 {
print("intermediate: \(globalObject!)")
}
print("globalObject: \(globalObject!)")
进而:
swiftc test.swift
for ((i = 0; i < 10000; i++)); do
./test | fgrep globalObject
done
我得到的是(只有 10000 次运行中的一次):

Fatal error: Object was retained too many timesa(44854,0x10a92f5c0) malloc: Incorrect checksum for freed object 0x7fcc1ec02b98: probably modified after being freed.

Corrupt value: 0x7ffffffe00000000

test(44854,0x10a92f5c0) malloc: *** set a breakpoint in malloc_error_break to debug

globalObject: C(id: ObjectIdentifier(0x00007f7f452006c0), s: abc)

test(61212,0x114d7e5c0) malloc: Incorrect checksum for freed object 0x7fe063e00008: probably modified after being freed.

Corrupt value: 0x4ffffffe00000000

test(61212,0x114d7e5c0) malloc: *** set a breakpoint in malloc_error_break to debug


下一次运行:

test(7016,0x10682d5c0) malloc: tiny_free_list_remove_ptr: Internal invariant broken (next ptr of prev): ptr=0x7fb2e0805fd0, prev_next=0x7f92e0805fd0


这似乎是一些竞争条件,但我不知道谁在这里产生线程。
顺便提一句:
swiftc -version
Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5)
Target: x86_64-apple-darwin18.7.0

关于swift - 从 `self` 走私 `deinit`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57912403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com