4

In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?
let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1) ptr.pointee = 1

Laughing
  • 85
  • 6

4 Answers4

2

Here, ptr is constant, so you cannot assign a new UnsafeMutablePointer to it, but the structure it holds within can be modified. In short, you cannot reassign anything to a let entity, but you can access and modify its properties.

nanibir
  • 234
  • 1
  • 9
2

A pointer is not a struct.

It's a reference type unlike a struct which is value type.

Since you declare the pointer as mutable you can change the pointee (the contents of the memory) but you cannot change the reference itself.

vadian
  • 274,689
  • 30
  • 353
  • 361
1

In case of a Pointer, you cannot change the memory address it is pointing to, but you can change the data stored at that memory address. The Pointer is only storing a reference to a memory address, so as long as that address is constant, the Pointer didn't change its value.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

UnsafeMutablePointer is a struct, but it declares

public struct UnsafeMutablePointer<Pointee> : Strideable, Hashable {

    public var pointee: Pointee { get nonmutating set }
    public subscript(i: Int) -> Pointee { get nonmutating set }

}

Here "nonmutating set" means that setting the property does not mutate the state of the pointer variable itself.

Therefore ptr.pointee can be assigned a new value even if ptr is a constant, and the same is true for the subscript setter:

let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
ptr.pointee = 1
ptr[0] = 2
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382