Understanding gcroot

一世执手 提交于 2019-12-03 14:43:20

问题


I have been reading this article to understand the gcroot template. I understand the

gcroot provides handles into the garbage collected heap

and that

the handles themselves are not garbage collected.

What I don't understand is the following:

When the CLR object moves with the garbage-collected heap, the handle will return the new address of the object. A variable does not have to be pinned before it is assigned to a gcroot template.

Does that mean that the CLR object will be deleted by the garbage collector even if there is a gcroot handle referencing that object?

What is the "new address" that it refers to? And what does it mean that the "variable does not have to be pinned before it is assigned to a gcroot template"?


回答1:


Garbage collection doesn't just remove unreferenced objects, it also moves around objects that are still referenced, e.g. to defragment the free memory pool. When the article talks about objects moving in the CLR heap, it's probably saying "when garbage collection moves a still-referenced object, the gcroot handle will be automatically updated to still point to the CLR object."

You can prevent GC from moving objects around by using the pin_ptr keyword, like so:

Object ^obj = gcnew <something>;
pin_ptr pinned = obj;  /* obj won't move due to GC as long as pinned is in scope. */
/* do something interop-y here, pass to native code in a DLL, etc. */

See this article for more information about pinning.

Observation: The article may have a typo. If it had said "within the garbage-collected heap" instead of "with the garbage-collected heap", would that have improved your understanding? The way it's phrased in the article makes it sound like the very earth would move under your feet whenever GC cleaned house.



来源:https://stackoverflow.com/questions/4281834/understanding-gcroot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!