开发者

Is an int inside a class stored on the stack or the heap? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Stack & heap understanding question

I was told in Is using var actually slow? If so, why? that value types are stored on the stack and class types are stored in the heap.

class MyClass
{
  private int myInt;
  private int[] myInts;
}

Where is 开发者_Python百科MyClass.myInt stored? MyClass is a class/reference type, so it's on the heap. myInt is a value type, so is it stored on some kind of "inside stack"?

Also, what about the array? Is it a value or a class?


value types are put into stack and class types get put into heap

Only half of that is true, specifically the second half. Reference types are stored in the heap, that is always true.

The first part is not true, or rather only true sometimes. Value types that are local variables are stored on the stack, but value types that are member of a class or struct are stored inside that type. Value types that are boxed are stored inside an object on the heap.

So, an instance of your MyClass will contain an integer and a reference, and the instance of the class will always be stored on the heap.

The array is a separate object, and will also always be stored on the heap. If there actually is an array, that is. Until you have created an array and and assigned to myInts, it's null and there is no array.


Whatever is inside a reference type will get stored on the heap. The array will probably be stored in non-adjacent place to ''MyClass'' because it's size cannot be determined at compile time. If you're so confused with what goes where, any optimization is not your concern right now, you'll probably only make it worse, sorry.


Value types declared as local variables in a method are placed on the stack. When a value type is declared in a class, it is part of the data of that class, which is put on the heap. So with your class instances, myInt will be in the heap. When you declare any array, it is a class, so it gets it own place on the heap and your myInts value will be a reference to that object on the heap.


They are meaning often the variables in the functions when talking about references and value. Your Class code exits in the TEXT part of memory. When you are creating an object (instantiating it) it (The object and all of the member variables) will be in Heap. But while passing to functions a reference to the object address at heap could be find on Stack.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜