问题
Programming language books usually explain that value types are created on the stack, and reference types are created on the heap.
My question is Why.
回答1:
My question is Why.
Why do they "explain" that? Because sometimes the authors don't know any better themselves, and sometimes they're too lazy to explain it properly. The truth it rather more complicated.
Fortunately, Eric Lippert has written extensively around this:
- The stack is an implementation detail, part 1
- The stack is an implementation detail, part 2
- The truth about value types
While I would usually try to at least include a paraphrase of the full answer here, I'm not going to do so here - because explaining it very briefly is almost bound to give a misleading result. Just go and read those blog posts - and then everything else Eric has written. It'll take weeks, but you'll be glad you did.
回答2:
Why does book authors writes like that ?
1.They have not read Eric Lippert enough.
2.They may not be stating about C# / Java compiler and they might be thinking of some other magic language.
3.They (authors) read the same from some other books (so it's in loop now)
4.[IMP] It's very easy to remember (not useful though) in 1 line statement rather than sayings of Eric Lippert.
5.Much of the programmers (like me) just reads, for them , in reality does not matter what happens in RAM. They want the out put shown on the screen (monitor). They want to remember these facts (whichever is easier and close to reality) for the purpose of interview.
6.Most of Interview takers in the current software industry are not like Eric Lippert. So even they dont know in reality. So remembering the false one will be helpful.
来源:https://stackoverflow.com/questions/9901865/why-are-value-types-created-on-the-stack-and-reference-types-created-on-the-heap