Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-13355] deinit is not always called on type with throwing initializer, even if all properties have been set #55795

Closed
kmahar opened this issue Aug 6, 2020 · 4 comments
Assignees
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.

Comments

@kmahar
Copy link

kmahar commented Aug 6, 2020

Previous ID SR-13355
Radar rdar://problem/67361228
Original Reporter @kmahar
Type Bug
Status Resolved
Resolution Done
Environment

Swift 5.2.4 debug mode, macOS 10.15.4

Additional Detail from JIRA
Votes 0
Component/s
Labels Bug
Assignee @slavapestov
Priority Medium

md5: 2e0c4e037ed63f371994df964727f707

Issue Description:

Originally discussed on this forums post: https://forums.swift.org/t/deinit-and-throwing-initializers/38871

Consider the following code snippet:

struct Err: Error {
    let message: String
}

class MyClass {
    let x: Int

    init() throws {
        // note we never actually throw this error
        if false {
            throw Err(message: "beforeError")
        }
        self.x = 1

        throw Err(message: "afterErr")
    }

    deinit {
        print("in deinit")
    }
}

do {
    let c = try MyClass()
} catch {
    print("error: \(error)")
}

The output of the program is:

error: Err(message: "afterErr")

i.e. deinit is never called.

However, if you update the init from above to look like this, removing the first conditional block (which we were never going into anyway, since it's if false):

init() throws {
    self.x = 1 

    throw Err(message: "afterErr")
}

The program's output is then:

in deinit
error: Err(message: "afterErr")

The error comes from the same place in both examples, and the type is in the exact same state. So why is deinit only called in the second example? This seems like a bug.

@typesanitizer
Copy link

@swift-ci create

@slavapestov
Copy link
Member

I believe this is the same underlying issue as https://bugs.swift.org/browse/SR-13439.

@slavapestov
Copy link
Member

#33743

@kmahar
Copy link
Author

kmahar commented Sep 1, 2020

Thanks @slavapestov!

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.
Projects
None yet
Development

No branches or pull requests

3 participants