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

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 instance the following example:

Class1 obj = new Class1();

Class1 foo()
{
    return new Class1();
}

Is as easy to read as the more Pythonesque way of writing it:

Class1 obj = Class1();

Class1 foo()
{
    return Class1();
}

EDIT: Cowan hit the nail on the head with the clarification of the question: Why did they choose this syntax?


  • It's a self documenting feature.
  • It's a way to make it possible to name a method "Class1" in some other class

  • Class1 obj = Class1();
    

    在C#和Java中,您需要“新”关键字,因为没有它,它会将“Class1()”视为对名为“Class1”的方法的调用。


    The usefulness is of documentation - it's easier to distinguish object creations from method invocations than in Python.

    The reason is historic, and comes straight from the C++ syntax. In C++, "Class1()" is an expression creating a Class1 instance on the stack. For instance: vector a = vector(); In this case, a vector is created and copied to the vector a (an optimizer can remove the redundant copy in some cases).

    Instead, "new Class1()" creates a Class1 instance on the heap, like in Java and C#, and returns a pointer to it, with a different access syntax, unlike Java and C++. Actually, the meaning of new can be redefined to use any special-purpose allocator, which still must refer to some kind of heap, so that the obtained object can be returned by reference.

    Moreover, in Java/C#/C++, Class1() by itself could refer to any method/function, and it would be confusing. Java coding convention actually would avoid that, since they require class names to start with a upper case letter and method names to start with a lower case one, and probably that's the way Python avoids confusion in this case. A reader expects "Class1()" to create an object, "class1()" to be a function invocation, and "x.class1()" to be a method invocation (where 'x' can be 'self').

    Finally, since in Python they chose to make classes be objects, and callable objects in particular, the syntax without 'new' would be allowed, and it would be inconsistent to allow having also another syntax.

    链接地址: http://www.djcxy.com/p/13882.html

    上一篇: 当内存将被释放?

    下一篇: 为什么C#和Java会对“新”运算符感到困扰?