我有一个非常大的结构,我想确保不会被不必要地复制.如何为它创建一个写时复制容器?
写时复制通常是某些后备对象的结构包装器.
原文链接:https://www.f2er.com/swift/320039.htmlpublic 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.