C++ 中的全局变量是存储在堆栈、堆还是两者都不存储?
Are global variables in C++ stored on the stack, heap or neither of them?
最初我很确定正确答案必须是“None of them”,因为全局变量存储在数据存储器中,但后来我找到了 Robert Lafore 的这本书,叫做“C++ 中的面向对象编程”,它明确指出,根据 C++ 标准,全局变量存储在堆上。现在我很困惑,无法真正弄清楚所问问题的正确答案是什么。
为什么全局变量会存储在堆上?我错过了什么?
编辑:Link to the book - 第 231 页
本书第 205 页是这样说的:
If you’re familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.
这绝对是书上的错误。首先,应该从存储时长的角度来讨论存储,C++标准的做法是:"stack"指的是自动存储时长,而"heap"指的是动态存储时长。 "stack"和"heap"都是分配策略,常用于实现对象的存储时长。
全局变量具有静态存储期限。它们存储在与 "heap" 和 "stack" 分开的区域中。全局常量对象通常存放在"code"段,非常量全局对象存放在"data"段。
最初我很确定正确答案必须是“None of them”,因为全局变量存储在数据存储器中,但后来我找到了 Robert Lafore 的这本书,叫做“C++ 中的面向对象编程”,它明确指出,根据 C++ 标准,全局变量存储在堆上。现在我很困惑,无法真正弄清楚所问问题的正确答案是什么。
为什么全局变量会存储在堆上?我错过了什么?
编辑:Link to the book - 第 231 页
本书第 205 页是这样说的:
If you’re familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.
这绝对是书上的错误。首先,应该从存储时长的角度来讨论存储,C++标准的做法是:"stack"指的是自动存储时长,而"heap"指的是动态存储时长。 "stack"和"heap"都是分配策略,常用于实现对象的存储时长。
全局变量具有静态存储期限。它们存储在与 "heap" 和 "stack" 分开的区域中。全局常量对象通常存放在"code"段,非常量全局对象存放在"data"段。