众所周知,C++的内存模型可以分为五个块:栈、堆、空闲块、全局/静态块、常量块。我可以理解前三个块,我也知道变量像static int xx
存储在第 4 个块中,还有“hello world”-string 常量,但是在第 5 个块-const 块中存储了什么?并且,例如int a = 10
,“10”存储在哪里?谁可以给我解释一下这个?
非常感谢。
There is a difference between string literals and primitive constants. String literals are usually stored with the code in a separate area (for historical reasons this block is often called the "text block"). Primitive constants, on the other hand, are somewhat special: they can be stored in the "text" block as well, but their values can also be "baked" into the code itself. For example, when you write
// Global integer constant
const int a = 10;
int add(int b) {
return b + a;
}
the return expression could be translated into a piece of code that does not reference a
at all. Instead of producing binary code that looks like this
LOAD R0, <stack>+offset(b)
LOAD R1, <address-of-a>
ADD R0, R1
RET
the compiler may produce something like this:
LOAD R0, <stack>+offset(b)
ADD R0, #10 ; <<== Here #10 means "integer number 10"
RET
Essentially, despite being stored with the rest of the constants, a
is cut out of the compiled code.
As far as integer literals constants go, they have no address at all: they are always "baked" into the code: when you reference them, instructions that load explicit values are generated, in the same way as shown above.
和 int a = 10 一样,“10”存储在哪里?
这是一个实现细节。可能会成为生成代码的一部分并变成类似的东西
mov eax, 10
在装配中。
类似的定义也会发生同样的情况
const int myConst = 10;
除非您尝试像这样获取 myConst 的地址:
const int *ptr = &myConst;
在这种情况下,编译器必须将值 10 放入专用内存块中(大概是您计算中的第 5 个)。