I have an exam on tuesday and I've noticed that, this question is one that my teacher asks a lot in his texts.
Initially I was pretty sure that the correct answer had to be "None of them", since global variables are stored in the data memory, but then I've found this book from Robert Lafore, called "Object Oriented Programming in C++" and it clearly states that, according to the C++ standard, global variables are stored on the heap. Now I'm pretty confused and can't really figure out what's the correct answer to the question that has been asked.
Why would global variables be stored on the heap? What am I missing?
Thanks in advance.
EDIT: Link to the book - page 231
答案 0 :(得分:26)
这是本书第205页所说的内容:
如果您熟悉操作系统体系结构,您可能有兴趣知道局部变量和函数参数存储在堆栈中,而全局变量和静态变量存储在堆上。
这绝对是书中的一个错误。首先,应该根据存储持续时间讨论存储,C ++标准的方式:“堆栈”指的是自动存储持续时间,而“堆”指的是动态存储持续时间。 “堆栈”和“堆”都是分配策略,通常用于实现具有各自存储持续时间的对象。
全局变量具有静态存储持续时间。它们存储在与“堆”和“堆栈”分开的区域中。全局常量对象通常存储在“代码”段中,而非常量全局对象存储在“数据”段中。
答案 1 :(得分:-3)
全局变量不存储在堆栈中,因为属于函数的变量存储在堆栈中。全局变量不属于任何函数,因此它们存储在堆上。
以下是您问题的更好答案: Static and global variable in memory
编辑:现在我更多地研究了一下,实际上,微软没有关于全局变量存储在C ++中的信息。