What kind of memory semantics govern array assignm

2020-04-07 18:53发布

Given the following: byte[] sData; and a function declared as private byte[] construct_command()

if I were to then assign the result of construct_command() to sData would sData just point to the contents of what's returned from the function or would some space be alloctaed for sData in memory and the contents of the result of the function be copied into it?

标签: c# .net
7条回答
够拽才男人
2楼-- · 2020-04-07 19:16

While Rui's answer is fine overall, I do think part of it is incorrect. It doesn't make sense (hugely inconsistent) for an array to be allocated from stack memory, then accessed by reference. If that were true, the underlying memory could be freed from underneath any methods the reference was passed to.

I believe Henk Holterman described it correctly when he said very directly and unambiguously:

Arrays are reference-types, that means that the actual array is instantiated on the heap

Thank you Henk for that comment; I think it is a critical part otherwise missing from (and contradicted by) the accepted answer.

(I would have replied to a comment, but I don't have enough points to reply, and I think it's important enough to point out that the accepted answer has this problem for me to add a new comment here.) Perhaps an admin can remove the reference to "a local variable, it will live in the stack" from the answer.

查看更多
登录 后发表回答