Why do C# and Java bother with the “new” operator?

后端 未结 9 1145
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 13:59

Why does the new operator exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?

For insta

9条回答
  •  情歌与酒
    2020-12-03 14:55

    The new operator in C# maps directly to the IL instruction called newobj which actually allocates the space for the new object's variables and then executes the constructor (called .ctor in IL). When executing the constructor -- much like C++ -- a reference to the initialized object is passed in as an invisible first parameter (like thiscall).

    The thiscall-like convention allows the runtime to load and JIT all of the code in memory for a specific class only one time and reuse it for every instance of the class.

    Java may have a similar opcode in its intermediate language, though I am not familiar enough to say.

提交回复
热议问题