C++中的变量存储在哪里? [英] Where are variables in C++ stored?
问题描述
C++ 中的变量存储在哪里?
Where are variables in C++ stored?
在 RAM 或处理器的缓存中?
Inside the RAM or the processor's cache?
推荐答案
存储命名变量:
- 在堆栈上,如果它们是函数局部变量.
C++ 将此称为自动存储"1 并且不要求它实际上是 asm 调用堆栈,并且在一些罕见的实现中它不是.但在主流实现中确实如此. - 在每个进程的数据区域中,如果它们是全局的或
静态
.
C++ 将此称为静态存储类";它在 asm 中通过在section .data
、.bss
、.rodata
或类似内容中放置/保留字节来实现.
- On the stack, if they're function-local variables.
C++ calls this "automatic storage"1 and doesn't require it to actually be the asm call stack, and in some rare implementations it isn't. But in mainstream implementations it is. - In a per-process data area if they are global or
static
.
C++ calls this "static storage class"; it's implemented in asm by putting / reserving bytes insection .data
,.bss
,.rodata
, or similar.
如果变量是用int *p = new int[10];
或类似方法初始化的指针,指针变量p
会进入自动存储或静态存储如上.内存中的指向对象是:
If the variable is a pointer initialized with int *p = new int[10];
or similar, the pointer variable p
will go in automatic storage or static storage as above. The pointed-to object in memory is:
- 在堆上(C++ 称之为动态存储),用
new
或malloc
等分配
在 asm 中,这意味着调用分配器函数,如果它的空闲列表为空,它最终可能会通过某种系统调用从操作系统获取新内存.堆"不是现代操作系统/C++ 实现中的单个连续区域.
C 和 C++ 不进行自动垃圾收集,命名变量本身不能处于动态存储(堆")中.动态存储中的对象是匿名的,除了被其他对象指向之外,其中一些可能是适当的变量.(结构或类类型的对象,相对于像 int
这样的原始类型,可以让你在这个匿名对象中引用命名的类成员.在成员函数中,它们甚至看起来是相同的.)
C and C++ don't do automatic garbage collection, and named variables can't themselves be in dynamic storage ("the heap"). Objects in dynamic storage are anonymous, other than being pointed-to by other objects, some of which may be proper variables. (An object of struct or class type, as opposed to primitive types like int
, can let you refer to named class members in this anonymous object. In a member function they even look identical.)
这就是为什么您不能(安全/有用地)返回指向局部变量的指针或引用的原因.
This is why you can't (safely/usefully) return a pointer or reference to a local variable.
当然,这一切都在 RAM 中.缓存对用户空间进程是透明的,但它可能会明显影响性能.
This is all in RAM, of course. Caching is transparent to userspace processes, though it may visibly affect performance.
编译器可能会优化代码以将变量存储在寄存器中.这是高度依赖于编译器和代码的,但好的编译器会积极地这样做.
Compilers may optimize code to store variables in registers. This is highly compiler and code-dependent, but good compilers will do so aggressively.
脚注 1:有趣的事实:auto
在 C++03 及更早版本中,并且仍然在 C 中,意味着自动存储类,但现在(C++11)它推断类型.
Footnote 1: Fun fact: auto
in C++03 and earlier, and still in C, meant automatic storage-class, but now (C++11) it infers types.
这篇关于C++中的变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!