Marcus Rossel
Marcus Rossel

Reputation: 3258

What meaning does the parameter have for UnsafeMutablePointer<Type>.alloc()?

Let's say I want to create a pointer to an Int in Swift. From what I've seen I'd do this:

let pointer = UnsafeMutablePointer<Int>.alloc(1)
pointer.memory = 100
println(pointer)        //prints 0x00007f8672fb7eb0
println(pointer.memory) //prints 100

Now, when I call UnsafeMutablePointer<Int>.alloc(1), what does 1 denote? I assume its the number of Ints allocated in memory starting from the pointer adress.
So 1 would allocate 8 bytes, 2 would allocate 16 bytes, and so on...
Is this true?

If so, how much memory does Swift allocate for UnsafeMutablePointer<Type>s using a generic type?

Upvotes: 2

Views: 217

Answers (1)

Martin R
Martin R

Reputation: 539775

Now, when I call UnsafeMutablePointer<Int>.alloc(1), what does 1 denote? I assume its the number of Ints allocated in memory starting from the pointer address.

It is the number of items for which memory is allocated.

So 1 would allocate 8 bytes, 2 would allocate 16 bytes, and so on... Is this true?

Almost. One Int can be 4 or 8 byte, depending on the architecture.

If so, how much memory does Swift allocate for UnsafeMutablePointer<Type> using a generic type?

You cannot allocate memory for a generic type. At the point where alloc() is called, the type parameter T must be known, either given explicitly or inferred from the context.

Upvotes: 4

Related Questions