哪个内存区域是C ++中的const对象? [英] Which memory area is a const object in in C++?

查看:161
本文介绍了哪个内存区域是C ++中的const对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是问什么stack / heap / static意味着什么是什么是不同的。我要问哪个区域有一个const对象?



C ++代码:

  #include< cstdio> 

using namespace std;

const int a = 99;

void f()
{
const int b = 100;
printf(const in f():%d \\\
,b);
}

int main()
{
const int c = 101;
printf(global const:%d \\\
,a);
f();
printf(local const:%d \\\
,c);
return 0;
}

哪个内存区域 a b c 他们的生命是什么?


div class =h2_lin>解决方案

没有指定。一个好的优化编译器在编译你显示的代码时可能不会为它们分配任何存储。



事实上,这正是我的编译器( g ++ 4.7.2 ),将代码编译为:

  ; f()
__Z1fv:
LFB1:
leaq LC0(%rip),%rdi
movl $ 100,%esi
xorl%eax,%eax $ b b jmp _printf
LFE1:
.cstring
LC1:
.asciiglobal const:%d\12\0
LC2:
.asciilocal const:%d\12\0

; main()
_main:
LFB2:
subq $ 8,%rsp
LCFI0:
movl $ 99,%esi
xorl%eax,%eax
leaq LC1(%rip),%rdi
call _printf
call __Z1fv
movl $ 101,%esi
xorl%eax,%eax
leaq LC2 %rip),%rdi
call _printf
xorl%eax,%eax
addq $ 8,%rsp
LCFI1:
ret

如您所见,常量的值直接嵌入到机器代码中。堆栈上没有内存,堆或为其中任何一个分配的数据段。


I'm not asking what stack/heap/static mean or what is the different between them. I'm asking which area a const object in?

C++ code:

#include <cstdio>

using namespace std;

const int a = 99;

void f()
{
    const int b = 100;
    printf("const in f(): %d\n", b);
}

int main()
{
    const int c = 101;
    printf("global const: %d\n", a);
    f();
    printf("local const: %d\n", c);
    return 0;
}

which memory area are a, b, and c in? and what are the lifetime of them? Is there any differences in C language?

What if I take their address?

解决方案

That's not specified. A good optimizing compiler will probably not allocate any storage for them when compiling the code you show.

In fact, this is exactly what my compiler (g++ 4.7.2) does, compiling your code to:

; f()
__Z1fv:
LFB1:
        leaq    LC0(%rip), %rdi
        movl    $100, %esi
        xorl    %eax, %eax
        jmp     _printf
LFE1:
        .cstring
LC1:
        .ascii "global const: %d\12\0"
LC2:
        .ascii "local const: %d\12\0"

; main()
_main:
LFB2:
        subq    $8, %rsp
LCFI0:
        movl    $99, %esi
        xorl    %eax, %eax
        leaq    LC1(%rip), %rdi
        call    _printf
        call    __Z1fv
        movl    $101, %esi
        xorl    %eax, %eax
        leaq    LC2(%rip), %rdi
        call    _printf
        xorl    %eax, %eax
        addq    $8, %rsp
LCFI1:
        ret

As you can see, the values of the constants are embedded directly into the machine code. There is no memory on the stack, the heap or the data segment allocated for any of them.

这篇关于哪个内存区域是C ++中的const对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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