Will the new instance of the local class be garbage collected if I return an array of it?

Let's say an instance of a class will build arrays:

class FooArrBuilder
{
    public Foo[] FinalResult { get { return arr; } }
    Foo[] arr;
    public void BuildArr();
    ...
}

      

Then it is used like this:

Foo[] GetFooArr()
{
    var fb = new FooArrBuilder();
    fb.BuildArr();
    ...
    return fb.FinalResult;
}

      

When an array is created inside an instance local to a function, will the array be moved from the instance that built it, or is the entire instance kept in memory just to contain the array? I don't necessarily want to copy the array if that's the case, but perhaps I could make the class a structure? Help is appreciated :)

If you want to elaborate on the C # memory model here, it will probably help me avoid further confusion.

Thank you in advance

+3


source to share


3 answers


An instance of a class does not "own" or "contain" an array. It just refers to an array that is allocated on the heap. Other references to this array will not contain instances of this class.



If any other objects (or stack frames) refer to this array, the memory on the heap allocated for the array will remain allocated for that array. After these objects are garbage collected and these stack frames are floated, the garbage collector will claim the memory allocated for this array.

+5


source


Yes, it would. While the elements of an array of type Foo

do not contain a reference toFooArrBuilder



+3


source


I think I understand now.

When a FooArrBuilder is instantiated, it is done on the heap. A pointer to it, size int, is pushed onto the stack. The reference count of an object allocated on the heap is incremented by one.

When the FooArrBuilder instance creates an array, ALMOST performs the same process for the array; the heap object is allocated again with reference number 1, this time of type Foo []. However, this time the pointer is not pushed onto the stack — instead, inside the memory pointed to by the previous stack pointer, Foo [] arr, which is actually a pointer to the Foo [] object, is set to point to the new array.

When we're going to return, we get another reference to Foo [], called arr, from the instance. The reference count for the array is now 2. When the function returns, the reference to the class instance is lost, so the reference count is now 0. Therefore, the instance is marked as garbage. When the instance (at some undefined point) is later garbage collected, the reference it has to the array is lost - and so the reference count of the array is 1 again.

0


source







All Articles