C ++中的全局变量是存储在堆栈,堆还是都不存储? [英] Are global variables in C++ stored on the stack, heap or neither of them?

查看:1208
本文介绍了C ++中的全局变量是存储在堆栈,堆还是都不存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在星期二进行了一次考试,我注意到,这个问题是我的老师在他的文章中提出的很多问题。

起初我非常肯定,正确的答案必须是无,因为全局变量存储在数据存储器中,但是我发现这个本书来自Robert Lafore,名为面向对象的C ++编程,它明确指出,根据C ++标准,全局变量存储在堆中。现在我很困惑,不能真正弄清楚问题的正确答案。

为什么全局变量会存储在堆上?我错过了什么?



在此先感谢您。

编辑:本书链接 - 第231页 / div>

这本书在第205页上说过:


如果您熟悉操作系统架构,有兴趣知道局部变量和函数参数存储在堆栈中,而全局变量和静态变量存储在堆中。


这在本书中绝对是一个错误。首先,应根据C ++标准的存储时间来讨论存储:堆栈是指自动存储持续时间,而堆是指动态存储持续时间。 堆栈和堆都是分配策略,通常用于实现具有各自存储持续时间的对象。

全局变量具有静态存储持续时间。它们存储在与堆和堆栈分开的区域。全局常量对象通常存储在代码段中,而非常量全局对象存储在数据段中。


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

解决方案

Here is what the book says on page 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.

This is definitely an error in the book. First, one should discuss storage in terms of storage duration, the way C++ standard does: "stack" refers to automatic storage duration, while "heap" refers to dynamic storage duration. Both "stack" and "heap" are allocation strategies, commonly used to implement objects with their respective storage durations.

Global variables have static storage duration. They are stored in an area that is separate from both "heap" and "stack". Global constant objects are usually stored in "code" segment, while non-constant global objects are stored in the "data" segment.

这篇关于C ++中的全局变量是存储在堆栈,堆还是都不存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆