Last active
September 6, 2022 23:19
-
-
Save JadenGeller/be9a6d13421a65583d7c to your computer and use it in GitHub Desktop.
Inout is really UnsafeMutablePointer!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = 0 | |
var b = 0 | |
// UnsafeMutablePointer definition | |
func test2(x: UnsafeMutablePointer<Int>) { | |
x.memory += 1 | |
// We have to manually dereference x within this method | |
} | |
// Inout definition | |
func test(inout x: Int) { | |
x += 1 | |
// Inout works like C++ references, no need for an explicit dereference | |
// (Note that it is still way less gross than C++ because you still need to use & to pass the pointer in on call in Swift) | |
} | |
// We call them both the EXACT SAME WAY | |
test(&a) | |
test2(&b) | |
println(a) // -> 1 | |
println(b) // -> 1 | |
// Same result! | |
// We could make a function that returns an UnsafeMutablePointer from a Swift variable like so: | |
func makePointer<T>(x: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T> { | |
return x | |
} | |
let pointerToA = makePointer(&a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The calling syntax may be the same, but the semantics are slightly different. Here is an explanation from someone on stack overflow, (if you change inout in the below example to UnsafeMutablePointer the program will have undefined behavior):
Normally, in-out parameter is passed by reference, but it's just a result of compiler optimization. When a closure captures an inout parameter, "pass-by-reference" is not safe, because the compiler cannot guarantee the lifetime of the original value. For example, consider the following code:
In this code, var i is freed when foo() returns. If x is a reference to i, x++ causes access violation. To prevent that situation, Swift adopts "call-by-copy-restore" strategy here.