English is not my native language, so please excuse any typing errors. I am using a translator for my question.
I learned from watching "WWDC16 - Understanding Swift Performance" that when allocating memory for a class on the heap, it allocates 2 words more than on the stack.
The first word of the 2 words is a pointer to the type information of that class, and the second word is the reference count.
To verify this, I wrote the following code:
class RefType {
var num1: Int
var num2: Int
init(num1: Int, num2: Int) {
self.num1 = num1
self.num2 = num2
}
}
func test() {
var ref1 = RefType(num1: 5, num2: 9) // 03 00
var ref2 = ref1 // 03 02
print(Unmanaged.passUnretained(ref1).toOpaque()) // 0x0000600000206a00
print("job done") // <- breakpoint
}
test()
By inspecting the memory through the address of ref1, I got the following results:
I thought that the value 05 and 09 that were passed in while creating the class are assigned, and the word preceding 05 represents the reference count (second block highlighted in blue)
To make sure, I added another variable that references ref1 and wrote the provided code.
var ref1 = RefType(num1: 5, num2: 9) // 03 00
var ref2 = ref1 // 03 02
var ref3 = ref1 // added
While expecting the reference count to increase by 1 and become 03, it was 04 instead.
I dont understand why it increases by 2 each time a new reference is added and also what does the 03 00 00 00 at the first 4bytes means??
Summary
- Although I understand that the blue-highlighted part represents the reference count of the class, I don't know the meaning of the value(
03) pointed by the first 4 bytes. - I'm curious about why the reference count increases by 2 as the number of references increases.
I'm new here and my reputation is not enough, so I had to replace the pictures with links. Thank you for your understanding.