Swift代码在Release/[-O]优化模式下崩溃:outlined init with take of any protocol
Swift优化模式下泛型协议存在类型崩溃问题分析
问题重现
这段Swift代码在Debug模式下运行正常,但开启Release模式或设置编译器优化级别为「Optimize for Speed [-O]」时会崩溃:
protocol Delegate<T> { associatedtype T func f(t: T) } class ConcreteClass: Delegate { func f(t: Int) { } } class A<T> { private let delegate: any Delegate<T> init(delegate: any Delegate<T>) { self.delegate = delegate } } let a = A(delegate: ConcreteClass())
崩溃栈信息:
#0 0x0000000100003b49 in outlined init with take of any Delegate<Self.Delegate.T == Int> () #1 0x0000000100003ac4 in specialized A.init(delegate:) [inlined] at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:25 #2 0x0000000100003ab7 in specialized A.__allocating_init(delegate:) [inlined] at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:24 #3 0x0000000100003a96 in main at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:29 #4 0x000000010001952e in start ()
崩溃原因及结论
这是Swift编译器优化器的Bug,具体是优化器在处理带关联类型的泛型协议存在类型(any Delegate<T>)的所有权转移时出现逻辑错误。
Debug模式下编译器未启用激进优化,对存在类型的内存管理逻辑正常;但在-O优化模式下,生成outlined init with take函数时,优化器错误处理了存在类型的内存布局或引用计数操作,导致访问非法内存引发崩溃。
该问题属于编译器层面的缺陷,而非代码逻辑错误,通常在Swift的特定版本(如部分5.x版本)中存在,后续官方更新的Swift版本可能已修复该问题。
内容的提问来源于stack exchange,提问作者plamkata__
相关产品推荐
相关产品推荐

