哪种数据类型垃圾收集器释放内存 [英] Which data type Garbage collector release the memory

查看:84
本文介绍了哪种数据类型垃圾收集器释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



我了解到使用类创建的对象是由垃圾收集器收集的,但是结构对象不能被GC收集。我知道结构是值类型并存储在堆栈中,类是存储在堆中的对象类型。



但是,我猜GC只收集托管代码。那么这是否意味着Structure类型是非托管代码?







GC会处理仅存储在堆中但不存储在堆栈中的对象吗? />


如果是,那么int数据类型呢?类型为int的对象,不是由GC管理的吗?



有人请澄清我的困惑。



谢谢和问候,

Atul Sharma

解决方案

不,它只是意味着结构不是t(通常)存储在堆上 - 它们存储在称为堆栈的不同内存区域,不需要垃圾回收。

堆就像一个字节的云,当你为类实例分配堆内存时系统找到一个足够大的块并使用它。垃圾收集器就在那里,以便当你不再需要它们并且为了其他目的而回收时可以回收块。

堆栈是不同的:每个线程都有它自己的,它用于保存方法返回地址,参数,对类的本地引用(对基于堆的内存的引用)和基于结构的值 - 它不需要垃圾收集,因为当您从方法返回时,它使用的所有内存都会自动回收。如果你愿意,可以把它想象成一堆硬币,每枚硬币都是一个记忆位置。当您输入方法时,您将一小块纸放在堆栈上,然后为您的方法所需的每个变量添加一个硬币。当你返回时,你会发现这张纸上面的所有硬币都被取下。



这是一个模糊的概述 - 结构可以直接存储在堆上,如果它们是引用类型的一部分,如类或数组;或者它们可以通过一个名为拳击的过程临时存储在堆上 - 但它对初学者来说已经足够了!

如果你想让你的大脑受伤,请看一下:使用struct和class - 那是什么意思? [ ^ ]

Dear All,

I learnt that the Objects created using Classes are collected by Garbage collector, but the object of struct can not be collected by GC. I know that structure are value type and stored in stack and classes are object type stored in heap.

But, I guess GC collects managed codes only. So does that mean that the Structure types are unmanaged code?

OR

GC take care of objects that stored in Heap only and not in Stack ?

If yes, then what about int data type? Is object of type int, not managed by GC?

Some one please clarify my confusion.

Thanks & Regards,
Atul Sharma

解决方案

No, it just means that structs aren;t (normally) stored on the heap - they are stored on a different area of memory called the stack, which doesn't require garbage collection.
The heap is like a "cloud" of bytes, and when you allocate heap memory for a class instance the system finds a chunk big enough and uses that. The Garbage collector is there so that the chunks can be reclaimed when you no longer need them and recycled for other purposes.
The stack is different: each thread has it's own, and it is used to hold method return addresses, parameters, local references to classes (which are references to the heap based memory), and struct based values - it doesn't need garbage collection because when you return from a method all the memory it used is automatically reclaimed. If you like, think of it as a stack of coins, where each coin is a memory location. When you enter you method, you put a small piece of paper on the stack, and then add a coins for each variable your method needs. When you return you find the piece of paper an take off all the coins above it.

That's a vague overview - structs can be stored on the heap directly if they are part of a reference type like a class, or an array; or they can temporarily be stored on the heap via a process called boxing - but it's good enough for beginners!
If you want to make your brain hurt, have a look here: Using struct and class - what's that all about?[^]


这篇关于哪种数据类型垃圾收集器释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆