簡體   English   中英

Swift 3參考類型和內存管理

[英]Swift 3 reference type and memory management

我研究了Class類型是Swift中的引用類型。

因此,例如,我有以下語句:

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;

之前

ptrB = ptrA;

我研究的教程沒有提到這一點,但是我認為Swift可以執行“刪除ptrB”之類的行為。 自動,所以我不需要處理這個,對吧?

Swift使用一種稱為自動引用計數(ARC)的技術來跟蹤對象當前具有的引用數,並在計數達到零時釋放內存。 迅速執行b = a時,假定沒有其他引用,則舊b的引用計數將達到零。 Swift看到它為零,然后將其刪除。 這就是為什么您無需迅速delete自己的原因。 您可以從此處了解有關ARC的更多信息。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM