我知道全局变量、静态变量等存储在进程内存区的数据区中. 但是,我知道在 struct 中实现的类型的变量存储在堆栈中.
如果由 struct 实现的变量是全局变量,那么它不能在数据区域中声明吗?
我想知道为什么我可以肯定它是在Stack区域创建的.
我知道全局变量、静态变量等存储在进程内存区的数据区中. 但是,我知道在 struct 中实现的类型的变量存储在堆栈中.
如果由 struct 实现的变量是全局变量,那么它不能在数据区域中声明吗?
我想知道为什么我可以肯定它是在Stack区域创建的.
struct 存储在堆栈上
这是一种不准确的过度简单化.
struct 直接存储在它们的"父级"中,父级可以是:
class
的实例、捕获的闭包上下文等)Data
段它们甚至可能不作为一个整体存储在任何地方,并且它们的构成值只存储在寄存器中,这取决于优化器认为什么是最好的.
这是一篇关于C#的文章(它有GC和JIT),但其余的许多 idea 也适用于Swift:https://ericlippert.com/2010/09/30/the-truth-about-value-types/
在过go ,我通常驳斥这个神话的方式是说,真正的陈述应该是“in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.”