为什么在Java中将new称为运算符? [英] Why is new called an operator in Java?
问题描述
为什么new
关键字在Java中称为运算符?
我知道new
在Java中为对象动态分配内存并返回对其的引用,但是为什么将其称为运算符?
实际上,Java语言规范并未将new
称为运算符.它写入:>
由ASCII字符组成的38个令牌是运算符.
Operator: = > < ! ~ ? : -> == >= <= != && || ++ -- + - * / & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>= >>>=
new
仅仅是 类实例创建表达式.
我认为这是一个合理的定义,因为运算符将采用操作数(或者从源代码的角度来看,出现在表达式旁边),但是后跟参数列表的类名本身不是有效的表达式,也不是在运行时对其进行评估以产生一个值.
我怀疑调用new
运算符的做法源自C ++,其中新的运算符可以独立于构造函数调用而重载,以自定义内存分配策略.诸如Java或C#之类的托管语言不再允许这种分隔,但是术语运算符"已陷于困境.
例如, C#语言规范实际上讨论了new
运算符,并指定了其优先级,但是实际上指定其含义时,仅讨论的是3种表达式类型,而这3种表达式类型不能使用新关键字形成(对象创建,数组创建和委托创建表达式). /p>
Why is new
keyword called an operator in Java?
I know that new
dynamically allocates memory in Java for an object and returns a reference to it but why is it called an operator?
Actually, the Java Language Specification does not call new
an operator. It writes:
38 tokens, formed from ASCII characters, are the operators.
Operator: = > < ! ~ ? : -> == >= <= != && || ++ -- + - * / & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>= >>>=
new
is simply a keyword that occurs in a class instance creation expression.
I consider this a reasonable definition, as an operator would take operands (or, from the perspective of source code, appear next to an expression), but the class name followed by the argument list is not by itself a valid expression nor it is evaluated to produce a value at runtime.
I suspect the practice of calling new
an operator originates from C++, where the new operator could be overloaded independent of the constructor call, to customize the memory allocation strategy. Managed languages such as Java or C# no longer allow such a separation, but the term operator has stuck.
For instance, the C# language specification actually talks about a new
operator, and specifies its precedence, but when actually specifying its meaning only talks about the 3 expression types than can be formed with a new keyword (object creation, array creation, and delegate creation expressions).
这篇关于为什么在Java中将new称为运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!