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"?
The Generational Garbage Collection ProcessFirst, any new objects are allocated to the eden space. Both survivor spaces start out empty. When the eden space fills up, a minor garbage collection is triggered. Referenced objects are moved to the first survivor space.
When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.
NET's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap.
A garbage collection root is an object that is accessible from outside the heap. The following reasons make an object a GC root: System Class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With