3 ms·
The article includes the following example: let a = UnsafeMutablePointer<Int>.allocate(capacity: 1) a.pointee = 42 FYI, you should never do this. Ass
by gilgoomesh 10y ago
The article includes the following example:
let a = UnsafeMutablePointer<Int>.allocate(capacity: 1)
a.pointee = 42
FYI, you should never do this.
Assignment to the `pointee` is only safe where the `pointee` is already initialized. If the pointee is uninitialized, you should be using `initialize`. e.g.
let a = UnsafeMutablePointer<Int>.allocate(capacity: 1)
a.initialize(to: 42)
While it doesn't actually matter for `Int`, it does matter for classes, unspecialized generics and other Swift reference counted types since Swift will try to release the destination before assigning a new value into it. If the destination is uninitialized garbage, this can cause a crash or other misbehavior. Following proper practice is a good idea – even if you're using a hard coded pure value type like `Int` – since it prevents problems down the road if you decide to change.
Similarly, you should `deinitialize` the buffer when you're finished, not simply `deallocate`.
- atrick6 10y agoFrom the doc comments: /// Accesses the `Pointee` instance referenced by `self`. /// /// - Precondition: Either the pointee has been initialized with an /// instance of type `Pointee`, or `pointee` is being assigned to /// and `Pointee` is a trivial type. public var pointee: Pointee So, `a.pointee = 42` is fine since we all know that `Int` is a trivial type.
- nine_k 10y agoJaywalking when a street is empty is safe; it does not mean that jaywalking is safe in general, and that one should get used to it. In this case, `.initialize` is likely also faster because any previous-value-checking logic than might be there is explicitly not used.
- mikeash 10y agoWhen it's explicitly allowed by the rules, it's no longer "jaywalking." You're right that it doesn't mean this is safe in general, but the original comment is wrong that you should never do this. What previous-value-checking logic are you referring to? I would expect .pointee = 42 to compile down to a single store instruction.
- hota_mazi 10y ago> FYI, you should never do this. That's a bit too strong. This is safe if the type is trivial, which it was in the article. The author should have added the caveat you wrote, though.