简体   繁体   English

在方法调用期间修改参数时是否有任何保证?

[英]Are there any guarantees when modifying arguments during method invocation?

In Java when passing arguments to a method and modifying the passed arguments during the method call is it guaranteed that the result is what is expected? 在Java中,当将参数传递给方法并方法调用期间修改传递的参数 ,它是否保证结果符合预期?
Eg 例如
a.method(++i); etc 等等

Is it guaranteed for instance that inside method the variable i will have the updated value? 是否保证例如内部method变量i将具有更新值?

Or a.method(i++) Will method get the value of i after incrementing or before? 或者a.method(i++) Will method在递增之后或之前得到i的值?

Also same for all similar cases. 对于所有类似的情况也是如此。
I kind of remember this is forbidden in C++ as implementation specific but perhaps I remember wrong. 我有点记得在C ++中禁止这是特定于实现的,但也许我记得错了。

The java language specification for prefix/postfix increment/decrement operators: 前缀/后缀增量/减量运算符的java语言规范:

... the value 1 is added to the value of the variable and the sum is stored back into the variable ... The value of the prefix increment expression is the value of the variable after the new value is stored . ...将值1添加到变量的值中,并将总和存储回变量...前缀增量表达式的值是存储新值后变量的值

... the value 1 is added to the value of the variable and the sum is stored back into the variable ... The value of the postfix increment expression is the value of the variable before the new value is stored . ...将值1添加到变量的值中,并将总和存储回变量...后缀增量表达式的值是存储新值之前的变量

I think it's pretty clear. 我觉得很清楚。 The function will get the incremented value in the prefix case, and not in the postfix case. 该函数将在前缀的情况下获得递增的值,而不是在后缀的情况下。

The expression ++i is evaluated before the method is called. 在调用方法之前计算表达式++i

From the Java Language Specification's section "Runtime evaluation of method invocation" : 从Java语言规范的“方法调用的运行时评估”部分

... Second, the argument expressions are evaluated. ......其次,评估参数表达式。 ... Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code. ...第五,创建新的激活帧,必要时执行同步,并将控制转移到方法代码。

And from the Java Language Specification's section "Prefix increment operator" : 从Java语言规范的“前缀增量运算符”部分

The value of the prefix increment expression is the value of the variable after the new value is stored. 前缀增量表达式的值是存储新值后变量的值。

在Java中没有问题,方法将收到更新的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM