前一篇提到,Class 與 struct 最大的區別在於呼叫的方式分別為 call by value以及 call by reference,也嘗試著印出 class 與 struct 內變數的值是否相同來印證,這次我們試著印出各個變數的記憶體位址來進一步證明。
關於印出記憶體位址,這次我們使用 “ withUnsafePointer “ 這個函數
struct Svalue {
var x:Int = 0
}
var f1 = Svalue()
var f2 = f1
f2.x = 30
withUnsafePointer(to: &f1.x) {
print("The memory address of f1 = \($0)"," , the value of x in f1 is \(f1.x)" )
}
withUnsafePointer(to: &f2.x) {
print("The memory address of f2 = \($0)"," , the value of x in f2 is \(f2.x)" )
}
結果為
class Cvalue {
var y:Int = 0
}
var f3 = Cvalue()
var f4 = f3
f4.y = 50
withUnsafePointer(to: &f3.y) {
print("The memory address of f3 = \($0)"," , the value of y in f3 is \(f3.y)" )
}
withUnsafePointer(to: &f4.y) {
print("The memory address of f4 = \($0)"," , the value of y in f4 is \(f4.y)" )
}
結果為
由以上結果可以知道
f1 , f2 在struct內的記憶體位址是不同,而f3 , f4 在class則是指向同一個記憶體位址。