0
我研究過Swift中的類類型是引用類型。Swift 3引用類型和內存管理
因此,舉例來說,我有以下語句:
class Rectangle {
var x: Int
var y: Int
}
var a = Rectangle(x: 10, y: 10)
var b = Rectangle(x: 30, y: 30)
// (a.x, a.y) == (10, 10) and (b.x, b.y) == (30, 30)
b = a
b.x = 50
b.y = 50
// (a.x, a.y) == (50, 50) due to both instance a and b
// refer to the same piece in the memory
我認爲這種行爲是類似於C++的指針,例如:
SomeDefinedClass *ptrA = new SomeDefinedClass(10, 10);
SomeDefinedClass *ptrB = new SomeDefinedClass(30, 30);
// (ptrA->x, ptrA->y) == (10, 10)
// (ptrB->x, ptrB->y) == (30, 30)
ptrB = ptrA;
ptrB->x = 50;
ptrB->y = 50;
// (ptrA->x, ptrA->y) == (50, 50) due to both ptrA and ptrB
// point to the same object in the memory
但在C++中,這種指針賦值(的ptrB = PTRA)可引起 內存泄漏而不
delete ptrB;
b安伏
ptrB = ptrA;
我學的教程中沒有提到這一點, 但我認爲斯威夫特能做到像一些行爲「刪除的ptrB;」自動, 所以我不需要處理這個,對吧?
非常感謝! – Nestarneal