What does the keyword “new” do to a struct in C#?

前端 未结 6 1814
傲寒
傲寒 2020-11-28 04:41

In C#, Structs are managed in terms of values, and objects are in reference. From my understanding, when creating an instance of a class, the keyword new causes

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 05:13

    Catch Eric Lippert's excellent answer from this thread. To quote him:

    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.)

    (Making this answer since it really is one)

提交回复
热议问题