[英]C++ memory, allocation
Since first and last address are same or the address in &pi and a are same, is the address in a is from constant data segment or free store area?由于首尾地址相同或&pi和a中的地址相同,a中的地址是来自常量数据段还是空闲存储区?
int main()
{
const int pi = 10;
cout <<"This is constant memory area's address " << &pi << endl;
int *a = new int;
cout << "This is free store memory area's address " << a << endl;
a = (int*) π
cout << *a << endl;
cout << "This is free store memory area's address " <<a << endl;
return 0;
}
Your concepts are not correct.你的概念不正确。 There are side effects or limitations in your program.
您的程序存在副作用或限制。
The statement:该声明:
const int pi = 10;
Declares a constant.声明一个常量。 The compiler can put the constant wherever it wants.
编译器可以将常量放在任何它想要的地方。
Here are some possible locations:以下是一些可能的位置:
However, the moment you take the address of the constant, the compiler cannot store the value in these places:但是,在您获取常量地址的那一刻,编译器无法将值存储在以下位置:
move reg_a, #10
move reg_a, #10
Also, pointers can live in registers too.此外,指针也可以存在于寄存器中。 However, taking the address of a pointer prevents the pointer from living in a register, since using the
&
operator requires that the variable live in an addressable memory location and registers are not addressable via pointer.但是,获取指针的地址可以防止指针存在于寄存器中,因为使用
&
运算符要求变量存在于可寻址的内存位置中,而寄存器不能通过指针寻址。
BTW, you have a memory leak:顺便说一句,你有内存泄漏:
a = new int;
a = π
The last statement looses or leaks the location of the dynamically allocated integer.最后一条语句丢失或泄漏了动态分配的整数的位置。
Note: There are some processors in which registers live in an addressable location in memory;注意:有些处理器中的寄存器位于内存中的可寻址位置; but these are exceptions.
但这些都是例外。
Edit 1: Symbol Tables编辑 1:符号表
When you declare a variable as const
and assign it a literal, the compiler can store the variable in a table of <symbol, value> and not take up any variable space in the program.当你将一个变量声明为
const
并为其赋值时,编译器可以将该变量存储在一个 <symbol, value> 表中,而不占用程序中的任何变量空间。
When the compiler encounters the symbol, eg pi
, it can look up the symbol, pi
, in its table and substitute the value (10).当编译器遇到符号时,例如
pi
,它可以在其表中查找符号pi
并替换值 (10)。 So the expression:所以表达式:
int b = pi;
will become, after substitution:替换后会变成:
int b = 10;
Thus your pi
variable doesn't have any allocated space, in your program .因此,您的
pi
变量在您的程序中没有任何分配的空间。 In the above example, the value of the variable is placed into your program.在上面的例子中,变量的值被放入你的程序中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.