写入时复制通常是
struct某些支持对象的包装。
public final class MutableHeapStore<T>: NonObjectiveCbase{ public typealias Storage = T public private(set) var storage: Storage public init(storage: Storage) { self.storage = storage }}public struct COW<T>{ public typealias Storage = MutableHeapStore<T> public typealias Value = T public var storage: Storage public init(storage: Storage) { self.storage = storage } public var value: Value { get { return storage.storage } set { if isUniquelyReferenced(&storage) { storage.storage = newValue } else { storage = Storage(storage: newValue) } } } public init(_ value: Value) { self.init(storage: Storage(storage: value)) }}extension COW: CustomStringConvertible{ public var description: String { return String(value) }}诀窍在于
isUniquelyReferenced每次盒装值发生突变时都要断言。如果单独引用了基础存储对象,则无需执行任何操作。但是,如果存在另一个引用,则必须创建一个新的存储。
此代码是线程安全的吗?它与任何其他值类型(例如
Int或)一样安全
Bool。



