简体   繁体   English

变量声明和内存分配

[英]Variable Declaration & Memory Allocation

I want to know whether memory is allocated during the local variable declaration process. 我想知道在局部变量声明过程中是否分配了内存。

Suppose I write this code inside function, int a =10; 假设我在函数int a = 10中编写了此代码 memory is allocated and the value 10 is stored in that. 分配内存并在其中存储值10。

What about int a; int呢? ? This declaration statement will it allocate 4 bytes of memory? 该声明语句会分配4个字节的内存吗?

Thanks. 谢谢。

When you call a method, space for each local variable is allocated on the stack. 调用方法时,每个局部变量的空间都在堆栈上分配。

So if you declare an int variable in a method, it's stack frame will take up an extra 4 bytes of memory. 因此,如果您在方法中声明一个int变量,则它的堆栈帧将占用额外的4个字节的内存。

No additional memory is used anywhere else, and it is cleaned up when the method returns. 在其他任何地方都不会使用任何额外的内存,并且在方法返回时会清除它。

Something important to understand here is that MSIL does not support declaring a property just anywhere in a method. 这里要理解的重要一点是,MSIL不支持在方法的任何地方声明属性。 Whenever you declare a variable in C#, the declaration is moved to the method header in the compiled bytecode. 每当您在C#中声明变量时,该声明就会移至已编译字节码中的方法标头中。 Every variable is allocated when the method is called. 调用方法时将分配每个变量。

Local variables are usually stored on stack, so indeed bytes are allocated for int : 局部变量通常存储在堆栈中,因此确实为int分配了字节:

int a;

Because it simply uses default value (0), so it is the same as: 因为它仅使用默认值(0),所以它与:

int a = 0;

int is a value type, so on stack is stored its value. int是一种值类型,因此在堆栈上存储其值。 If you would create local variable with reference type: 如果要使用引用类型创建局部变量:

SomeClass a;

Then on stack it would be allocated only reference (with value null, as it is default value for reference types). 然后在堆栈上,它将仅分配给引用 (值为null,因为它是引用类型的默认值)。 For more information you can refer this question 有关更多信息,您可以参考此问题

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

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