Swift:如何在初始化时抛出一些属性?

此示例代码存在内存泄漏。

The father pointer allocate before Person inits successfully. If the init function throws an Error. The deinit function will never be executed. So the father pointer will never be released.

class Person {

    // a pointer to Person.
    let father = UnsafeMutablePointer<Person>.allocate(capacity: 1)

    let name: String

    init(name: String) throws {
        // do something ...

        // Because of some reasons. we want to throw a error, If do that. The "father" will never be released!!!
        if name == "Yanni" {
            throw NSError()
        }

        // do something ...
        self.name = name
    }

    deinit {
        father.deallocate()
    }
}

class InterestTests: XCTestCase {

    func testExample() {
        while true {
            _ = try? Person(name: "Yanni")
        }
    }

}

运行测试代码。我得到这个:

enter image description here

有什么办法可以避免这种内存泄漏?

评论