示例工程 18-value-semantics-cow
18-value-semantics-cow/Sources/Ch18Kit/NestedReference.swift
/// 嵌套引用会泄漏值语义:结构体复制了,但内部类实例仍共享。
public final class CounterBox {
public var value: Int
public init(value: Int = 0) {
self.value = value
}
}
public struct LeakyConfig {
public var box: CounterBox
public var title: String
public init(box: CounterBox, title: String) {
self.box = box
self.title = title
}
}
/// 同样的字段用值类型存储,复制后完全独立。
public struct SafeConfig {
public var value: Int
public var title: String
public init(value: Int, title: String) {
self.value = value
self.title = title
}
}
/// 内存布局:字段顺序、对齐与填充。
public struct MixedLayout {
public var flag: Bool
public var count: Int
public var ratio: Double
public init(flag: Bool, count: Int, ratio: Double) {
self.flag = flag
self.count = count
self.ratio = ratio
}
}
public struct TwoBools {
public var first: Bool
public var second: Bool
public init(first: Bool, second: Bool) {
self.first = first
self.second = second
}
}
public enum LayoutLab {
public static let stackBytes = MemoryLayout<COWStack<Int>>.size
public static let mixedBytes = MemoryLayout<MixedLayout>.size
public static let mixedStride = MemoryLayout<MixedLayout>.stride
public static let mixedAlignment = MemoryLayout<MixedLayout>.alignment
public static let twoBoolsBytes = MemoryLayout<TwoBools>.size
}