Value types in object stored in heap as well?

狂风中的少年 提交于 2020-01-11 05:12:05

问题


I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?


回答1:


They are stored in the heap, inside of the memory allocated for the reference type. In addition, value types are often stored in places other than "the stack". However, the CLI spec does not specify where the memory pool that stores value types resides - it's an implementation detail that should not matter.




回答2:


Andrew Hare is right. For the full details, see Eric Lippert's blog entry:

I'm disturbed by the myth that "value types go on the stack" ... It is usually stated incorrectly: the statement should be "value types can be stored on the stack", instead of the more common "value types are always stored on the stack".




回答3:


Those are stored on the heap, with the objects themselves. A good way to think about this is that when an object (that has value types as part of its state) is allocated on the heap, it's value types must live there as well, otherwise those value types would disappear as soon as the stack unwound for the code that created the object.




回答4:


Yes, they're stored as part of the heap. However, it's all an implementation detail, as Eric Lippert has described on multiple occasions. I suggest you read his blog posts about it, this being the most recent one, and these two also being important.



来源:https://stackoverflow.com/questions/4727910/value-types-in-object-stored-in-heap-as-well

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