2017-03-18 35 views
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;」自動, 所以我不需要處理這個,對吧?

回答

0

Swift使用了一種稱爲自動引用計數(Automatic Reference Counting,ARC)的技術來跟蹤對象當前擁有的引用數量,並在計數達到零時釋放內存。當您快速執行b = a時,假設沒有其他引用,舊的b的引用計數達到零。 Swift看到它是零並刪除它。這就是爲什麼你不需要自己快速登錄delete。您可以從here瞭解更多關於ARC的信息。

如果您想將其與C++進行比較,那麼不,它不起作用,像原始指針。相反,它更像C++ 11的智能指針std::shared_ptr

+0

非常感謝! – Nestarneal