How are arrays created and accessed

后端 未结 4 1663
醉话见心
醉话见心 2020-12-12 03:14

I understand(not completely why, though) that instances of primitive types such as int, float are stored on the stack and are not heap allocated. But I am a bit confused abo

相关标签:
4条回答
  • 2020-12-12 03:43

    Your "understanding" is flawed, basically. Value type values are sometimes stored on the stack - but not when part of an array or any other heap-based object. It's unfortunate that some people choose to make such a blanket statement around value types living on the stack, which then confuses others :(

    Besides, the stack/heap distinction is an implementation detail...

    See my article on memory for some more details, but definitely read Eric Lippert's blog post (linked in the previous paragraph) for more philosophical considerations. (Read his other posts on value types for even more information.)

    0 讨论(0)
  • 2020-12-12 03:44

    This article by Jeffry richter written back in 2002 explains this concept very clearly.

    0 讨论(0)
  • 2020-12-12 03:51

    Array itself is always a reference type, so it's stored on heap. Elements of an array are stored on heap too, but always in a contiguous block of memory.

    0 讨论(0)
  • 2020-12-12 03:53

    You have discovered the reason why the statement "value types are always stored on the stack" is obviously wrong. The truth is that the type of the object being stored is irrelevant to where it is stored. The correct rule is that values with short lifetimes are stored in storage from the short-term "stack" and values with long lifetimes are stored in storage from the long-term "heap".

    When you put it that way, it is practically a tautology. Obviously short-lived stuff is allocated from the short-term store, and long-lived stuff is allocated from the long-lived store! How could it be otherwise? But when you put it that way, clearly the type is irrelevant except insofar as the type gives you a hint about the lifetime.

    The contents of an array of ints is potentially long-lived, so the ints are allocated from the long-term store. The contents of a local variable of type int is typically short-lived, so it is typically allocated from the short-lived store.

    0 讨论(0)
提交回复
热议问题