A
A
Akaero2018-03-18 20:11:03
.NET
Akaero, 2018-03-18 20:11:03

How are objects of value types destroyed?

I am aware of the garbage collector that works on the heap, but how and when are objects of value types removed from the stack?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stanislav Makarov, 2018-03-18
@Akaero

1. In theory, an implementation is not required to use the stack to store local objects of value types (see https://blogs.msdn.microsoft.com/ericlippert/2009/... ).
2. Nevertheless, the current implementations use the stack, so everything is the same as in other languages: https://ru.wikipedia.org/wiki/%D0%A1%D1%82%D0%B5%D... .
3. Remember that values ​​of value types are sometimes (not always) stored on the stack. All values ​​of value-types that are part of an object of a reference type (for example, an int field in a class or elements of a double array) are born and die with this object.
Total:
More exotic situations will not be considered. And in general, as Lippert says (see link), it's better not to think in terms of the stack, because this is an implementation detail. It's better to talk about lifetime relative to called functions and relative to other objects.

G
Griboks, 2018-03-18
@Griboks

If memory serves me right, then meaningful types are the same references to objects in memory. Therefore, there is no difference.

M
MIsternik, 2018-03-18
@MIsternik

And they are not removed. A stack is a sequence, like this: 1|2|0|*|4|5|14.
* is the boundary between variables of different methods. i.e. if method 1 calls method 2, then 1|2|0 are the variables of the first method, and 4|5|14 of the second method.
When the second method returns, the stack pointer will point to the beginning of the list of variables of the first method and forget about the second. But that doesn't mean they're gone. Then they will simply be overwritten with other values ​​when these memory addresses are needed.

R
Roman, 2018-03-19
@yarosroman

From one smart book.
"Freeing memory on the stack is also very efficient and only requires restoring the stack pointer register to its previous value. Due to the nature of compiling methods to native code, the compiler often doesn't even need to remember the total space occupied by the method's local variables, and it can destroy the entire stack frame three standard instructions, known as the method epilogue."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question