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-9565] UnsafeMutablePointer on observed property of struct #52012

Closed
mattneub opened this issue Dec 22, 2018 · 4 comments
Closed

[SR-9565] UnsafeMutablePointer on observed property of struct #52012

mattneub opened this issue Dec 22, 2018 · 4 comments
Labels
compiler The Swift compiler in itself improvement

Comments

@mattneub
Copy link

Previous ID SR-9565
Radar None
Original Reporter @mattneub
Type Improvement
Status Closed
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Improvement
Assignee None
Priority Medium

md5: 7584086bf8002310dcab41ac775b8904

relates to:

  • SR-2790 Reject UnsafePointer initialization via implicit pointer conversion.

Issue Description:

The following observation was made today on Stack Overflow:

struct S {
    var prop : Int {
        didSet {
            print("did set!")
        }
    }
}
var s = S(prop:0)
let ptr = UnsafeMutablePointer(&s.prop)
ptr.pointee = 10
print(s.prop) // 0

This was said to be odd because things behave "as expected" if there is no setter observer on `prop`.

My response was to suggest that the way to get the expected result was to write:

struct S {
    var prop : Int {
        didSet {
            print("did set!")
        }
    }
}
var s = S(prop:0)
withUnsafeMutablePointer(to: &s.prop) { ptr in
    ptr.pointee = 10
}
print(s.prop) // 10

I also opined that the expression `UnsafeMutablePointer(&s.prop)` should never have compiled in the first place (I can't imagine which initializer the compiler imagines this would be), and that this, not the behavior when setting through the pointer's `pointee`, was the actual surprise.

However, I'm out of my depth.

@belkadan
Copy link
Contributor

belkadan commented Jan 7, 2019

Yeah, I think SR-2790 covers this. Escaping that pointer is definitely not safe!

@glessard
Copy link
Contributor

glessard commented Jun 5, 2021

The original example no longer behaves as described in Swift 5.4. Also, it produces a warning: "Initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer".

@mattneub
Copy link
Author

mattneub commented Jun 8, 2021

Agreed, I think this can be closed?

@glessard
Copy link
Contributor

glessard commented Jun 8, 2021

Will do.

@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
compiler The Swift compiler in itself improvement
Projects
None yet
Development

No branches or pull requests

3 participants