Destroying a struct object in C#?

2020-02-10 11:27发布

I am a bit confused about the fact that in C# only the reference types get garbage collected. That means GC picks only the reference types for memory de-allocation. So what happens with the value types as they also occupy memory on stack ?

8条回答
Luminary・发光体
2楼-- · 2020-02-10 12:30

I am a bit confused about the fact that in C# only the reference types get garbage collected.

This is not a fact. Or, rather, the truth or falsity of this statement depends on what you mean by "get garbage collected". The garbage collector certainly looks at value types when collecting; those value types might be alive and holding on to a reference type:

struct S { public string str; }
...
S s = default(S); // local variable of value type
s.str = M(); 

when the garbage collector runs it certainly looks at s, because it needs to determine that s.str is still alive.

My suggestion: clarify precisely what you mean by the verb "gets garbage collected".

GC picks only the reference types for memory de-allocation.

Again, this is not a fact. Suppose you have an instance of

class C { int x; }

the memory for the integer will be on the garbage-collected heap, and therefore reclaimed by the garbage collector when the instance of C becomes unrooted.

Why do you believe the falsehood that only the memory of reference types is deallocated by the garbage collector? The correct statement is that memory that was allocated by the garbage collector is deallocated by the garbage collector, which I think makes perfect sense. The GC allocated it so it is responsible for cleaning it up.

So what happens with the value types as they also occupy memory on stack ?

Nothing at all happens to them. Nothing needs to happen to them. The stack is a million bytes. The size of the stack is determined when the thread starts up; it starts at a million bytes and it stays a million bytes throughout the entire execution of the thread. Memory on the stack is neither created nor destroyed; only its contents are changed.

查看更多
\"骚年 ilove
3楼-- · 2020-02-10 12:32

Every value type instance in .NET will be part of something else, which could be a larger enclosing value type instance, a heap object, or a stack frame. Whenever any of those things come into being, any structures within them will also come into being; those structures will then continue to exist as long as the thing containing them does. When the thing that contains the structure ceases to exist, the structure will as well. There is no way to destroy a structure without destroying the container, and there is no way to destroy something that contains one or more structures without destroying the structures contained therein.

查看更多
登录 后发表回答