谁能解释常量或const变量存储在哪里? [英] can anyone explain where the constants or const variables stored?

查看:1438
本文介绍了谁能解释常量或const变量存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,C ++的内存模型可以分为五个块:堆栈,堆,空闲块,全局/静态块,const块.我可以理解前三个块,也知道像static int xx这样的变量存储在第4个块中,还有"hello world"字符串常量,但是什么存储在第5个块const块中?并且,像int a = 10一样,"10"存储在哪里?有人可以向我解释吗?

非常感谢.

解决方案

字符串文字和原始常量之间是有区别的.字符串文字通常与代码一起存储在单独的区域中(出于历史原因,此块通常称为文本块").另一方面,原始常量有些特殊:它们也可以存储在文本"块中,但是它们的值也可以烘焙"到代码本身中.例如,当您写

// Global integer constant
const int a = 10;

int add(int b) {
    return b + a;
}

返回表达式可以转换为根本不引用a的一段代码.而不是生成看起来像这样的二进制代码

LOAD R0, <stack>+offset(b)
LOAD R1, <address-of-a>
ADD R0, R1
RET

编译器可能会生成如下内容:

LOAD R0, <stack>+offset(b)
ADD R0, #10 ; <<== Here #10 means "integer number 10"
RET

从本质上讲,尽管a与其他常量一起存储,但仍将其从已编译的代码中删除.

就整数文字常量而言,它们根本没有地址:它们始终被烘焙"到代码中:当您引用它们时,将以与上述相同的方式生成加载显式值的指令. /p>

As we all know, C++'s memory model can be divided to five blocks: stack, heap, free blocks, global/static blocks, const blocks. I can understand the first three blocks and I also know variables like static int xx are stored in the 4th blocks, and also the "hello world"-string constant, but what is stored in the 5th blocks-const blocks? and , like int a = 10, where does the "10" stored? Can someone explain this to me?

Thanks a lot.

解决方案

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.

这篇关于谁能解释常量或const变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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