Why are we not forced to instantiate a struct with "new", like when using a class?
When you "new" a reference type, three things happen. First, the memory manager allocates space from long term storage. Second, a reference to that space is passed to the constructor, which initializes the instance. Third, that reference is passed back to the caller.
When you "new" a value type, three things happen. First, the memory manager allocates space from short term storage. Second, the constructor is passed a reference to the short term storage location. After the constructor runs, the value that was in the short-term storage location is copied to the storage location for the value, wherever that happens to be. Remember, variables of value type store the actual value.
(Note that the compiler is allowed to optimize these three steps into one step if the compiler can determine that doing so never exposes a partially-constructed struct to user code. That is, the compiler can generate code that simply passes a reference to the final storage location to the constructor, thereby saving one allocation and one copy.)
本文探讨了C#中结构体与new关键字的关系。详细解释了使用new关键字实例化结构体的过程,包括短时存储分配、构造函数调用及最终的值复制,并对比了结构体与引用类型在实例化过程中的差异。
1170

被折叠的 条评论
为什么被折叠?



