简体   繁体   English

g++ 中的 const 中的存储分配

[英]Storage allocation in a const in g++

I understand that c++ compilers do not usually allocate storage for a const int under certain conditions and resort to const folding.我了解 c++ 编译器通常不会在某些条件下为 const int 分配存储空间,而是使用 const 折叠。 I tried out a simple program to test this:我尝试了一个简单的程序来测试这个:

int main()
{
    const int num = 5;
    int a[num];
}

I compiled using the -g flag and ran it in gdb.我使用 -g 标志编译并在 gdb 中运行它。 When tried to access the address of the variable num here, It showed some valid address.当试图在这里访问变量 num 的地址时,它显示了一些有效的地址。 I did not expect this.我没想到会这样。 Any insights here?这里有什么见解吗?

I understand that c++ compilers do not usually allocate storage for a const int under certain conditions and resort to const folding.我了解 c++ 编译器通常不会在某些条件下为 const int 分配存储空间,而是使用 const 折叠。

It's not clear to me whether constant folding "usually" happens, nor that the occurrence of constant folding "usually" causes the compiler to not allocate storage.我不清楚常量折叠是否“通常”发生,也不清楚常量折叠“通常”的发生是否会导致编译器不分配存储。 The compiler will determine, somehow, whether constant folding is appropriate, and whether to allocate storage.编译器将以某种方式确定常量折叠是否合适,以及是否分配存储空间。 Certain things you might do, such as passing a pointer or reference to the const object to a function, can affect its decision.您可能会做的某些事情,例如将指针或对const object 的引用传递给 function,可能会影响其决定。

In any case, if you compile with -g , then that is definitely something that can steer the compiler toward allocating storage for the const int variable.无论如何,如果您使用-g进行编译,那么这绝对可以引导编译器为const int变量分配存储空间。 This is the easiest way to ensure that print num in GDB actually works.这是确保 GDB 中的print num确实有效的最简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM