There is a memory leak with this example code.
The pointer1 and pointer2 allocate before Person inits successfully. If the init function throws an Error. The deinit function will never be executed. So the pointer1 and pointer2 will never be released.
import XCTest
class Person {
// case1
let pointer1: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.allocate(capacity: 1)
// case2
let pointer2: UnsafeMutablePointer<Int>
let name: String
init(name: String) throws {
// case2
self.pointer2 = UnsafeMutablePointer<Int>.allocate(capacity: 1)
if name == "UnsupportName" {
throw NSError()
}
self.name = name
}
deinit {
pointer1.deallocate()
pointer2.deallocate()
}
}
class InterestTests: XCTestCase {
func testExample() {
while true {
_ = try? Person(name: "UnsupportName")
}
}
}
Sometimes the logic is very complicated. In my real cases. There are a lot of allocate and throws with if and guard. Some it's hard to control it.
Is there any way to avoid this memory leak?
Here is a similar question: https://forums.swift.org/t/deinit-and-failable-initializers/1199
I found a solution to my problem.