swift c语言数组,Swift 里 Array (一)内存结构

public struct Array: _DestructorSafeContainer {

#if _runtime(_ObjC)

@usableFromInline

internal typealias _Buffer = _ArrayBuffer

#else

@usableFromInline

internal typealias _Buffer = _ContiguousArrayBuffer

#endif

@usableFromInline

internal var _buffer: _Buffer

}

Array 是一个结构体。先看 runtime 不是 Objc 的情况。

Swift Array

20190320221858774687.jpg?

runtime Objc 情况

20190320221859306914.jpg?

内存结构

20190320221859728789.jpg?

Array 是一个结构体,持有了一个类_ContiguousArrayStorage。

类其中只有一个结构体_ArrayBody, 其中存储了数组的长度和分配的内存大小。

在初始化时,会在分配好的内存的尾部,附加分配一些内存,存储数组中的数据。

_storage = Builtin.allocWithTailElems_1(

_ContiguousArrayStorage.self,

realMinimumCapacity._builtinWordValue, Element.self)

Array 所有的操作,基本上都是基于_ContiguousArrayStorage 的。

其中一个函数,可以确定是否还有其他人引用当前的_ContiguousArrayStorage。在修改数组时,需要确定是否需要 copy 所有元素,这个函数十分重要。

/// Returns `true` iff this buffer's storage is uniquely-referenced.

///

/// - Note: This does not mean the buffer is mutable. Other factors

/// may need to be considered, such as whether the buffer could be

/// some immutable Cocoa container.

@inlinable

internal mutating func isUniquelyReferenced() -> Bool {

return _isUnique(&_storage)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值