参考通话与复印/恢复之间的区别
参考通话与复印/恢复之间的结果有什么区别?参考通话与复印/恢复之间的区别
背景:我目前正在学习分布式系统。关于远程过程调用的参考参数的传递,本书指出:“引用调用已被复制/恢复取代,尽管这并不总是相同的,但它足够好”。我理解如何通过引用和复制/恢复来调用原则上的工作,但我没有看到结果的差异可能在哪里?
取自here的示例。
主代码:
#include <stdio.h>
int a;
int main() {
a = 3;
f(4, &a);
printf("%d\n", a);
return 0;
}
打电话值:
f(int x, int &y){
// x will be 3 as passed argument
x += a;
// now a is added to x so x will be 6
// but now nothing is done with x anymore
a += 2*y;
// a is still 3 so the result is 11
}
值在传递并且对传入的变量的值没有影响
呼叫参考编号:
f(int x, int &y){
// x will be 3 as passed argument
x += a;
// now a is added to x so x will be 6
// but because & is used x is the same as a
// meaning if you change x it will change a
a += 2*y;
// a is now 6 so the result is 14
}
引用被传入。函数中的变量有效地与外部相同。
调用具有复制/还原:
int a;
void unsafe(int x) {
x= 2; //a is still 1
a= 0; //a is now 0
}//function ends so the value of x is now stored in a -> value of a is now 2
int main() {
a= 1;
unsafe(a); //when this ends the value of a will be 2
printf("%d\n", a); //prints 2
}
值在传递并且对直到函数的端传递的变量的值没有影响,在该点处的最终值函数变量存储在传入的变量中。
引用调用和复制/恢复之间的基本区别是,对函数变量所做的更改不会显示在传入的变量中,直到函数结束后,引用调用立即可以看到更改。
您在这两者中都使用了'&y' – CodyBugstein 2015-10-22 04:58:08
在示例“使用复制/恢复呼叫”中,它打印出'0'而不是'2'。 – Carlochess 2016-02-05 20:21:06
@Carlochess你使用哪种支持复制/恢复的语言? – mydogisbox 2016-02-05 21:43:26
通过复制/恢复调用是引用调用的一种特殊情况,其中提供的引用对于调用者是唯一的。引用值的最终结果将不会保存,直到函数结束。
当通过引用调用RPC中的方法时,此类调用很有用。实际的数据被发送到服务器端,最终结果将发送给客户端。这将减少流量,因为服务器每次都不会更新参考。
尽管我能够接受你的答案,但我不得不等待几个小时才能奖励赏金。感谢您的杰出回答,当然赏金是您的! – mort 2012-01-16 17:10:07
啊,我不知道赏金系统。很高兴知道! – mydogisbox 2012-01-16 18:21:59