使用new关键字初始化值类型时会发生什么?

时间:2018-04-29 06:41:44

标签: c# .net

当我们使用new关键字初始化值类型时: -

int i=new int();

然后对这个对象的内存分配会发生什么。是在堆栈上还是在堆上分配内存?

2 个答案:

答案 0 :(得分:3)

这取决于编写此语句的位置。如果它在方法的主体中,则值将在堆栈上分配:

void Method()
{
    int i = new int(); // Allocated on stack
}

IL-代码:

ldc.i4.0
stloc.0    // store as local variable

如果你在一个类的主体中写它,它将被分配在堆上,因为每个引用类型都在堆上分配:

class Class
{
    int i = new int(); // Allocated on heap
}

IL-代码:

ldc.i4.0
stfld      int32 Class::i  // store in field

同样适用于初始化class的方法或构造函数中的字段。对于structs,它取决于当前分配的位置。

答案 1 :(得分:1)

它正在堆栈中分配。

在以下答案中查看IL: Where and why use int a=new int?

int A = new int()编译为:

IL_0001:  ldc.i4.0         // Push 0 onto the stack as int32.   
IL_0002:  stloc.0          // Pop a value from stack into local variable

int C = 100 编译为:

IL_0005:  ldc.i4.s   100   // Push num onto the stack as int32
IL_0007:  stloc.2          // Pop a value from stack into local variable

它们之间基本没有区别。

您可以将其用作参考:

https://en.wikipedia.org/wiki/List_of_CIL_instructions

更新: 正如@Adrian所写,这取决于范围。 int a = 10和int a = new int()之间没有区别,但这不是问题。