引用调用和复制/恢复有什么区别 [英] What's the difference between call by reference and copy/restore

查看:77
本文介绍了引用调用和复制/恢复有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用调用和复制/恢复的结果有何不同?

What's the difference in the outcome between call by reference and copy/restore?

背景:我目前正在研究分布式系统.关于远程过程调用的引用参数传递,书中指出:引用调用已被复制/恢复取代.虽然这并不总是相同,但已经足够了".我了解按引用调用和复制/恢复的原理是如何工作的,但我看不出结果的差异在哪里?

Background: I'm currently studying distributed systems. Concerning the passing of reference parameters for remote procedure calls, the book states that: "the call by reference has been replaced by copy/restore. Although this is not always identical, it is good enough". I understand how call by reference and copy/restore work in principle, but I fail to see where a difference in the result may be?

推荐答案

示例取自 这里.

主要代码:

#include <stdio.h>

  int a;

  int main() {
      a = 3;
      f( 4, &a );
      printf("&#37;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
}

值是传入的,对传入的变量的值没有影响.

Value is passed in and has no effect on the value of the variable passed in.

参考调用:

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
}

传入引用,实际上函数中的变量和外面的变量是一样的.

Reference is passed in. Effectively the variable in the function is the same as the one outside.

通过复制/恢复调用:

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
}

传入的值对传入的变量的值没有影响,直到函数结束,此时函数变量的FINAL值存储在传入的变量中.

Value is passed in and has no effect on the value of the variable passed in UNTIL the end of the function, at which point the FINAL value of the function variable is stored in the passed in variable.

通过引用调用和复制/恢复之间的基本区别是,对函数变量所做的更改直到函数结束后才会显示在传入的变量中,而通过引用调用的更改将立即看到.

The basic difference between call by reference and copy/restore then is that changes made to the function variable will not show up in the passed in variable until after the end of the function while call by reference changes will be seen immediately.

这篇关于引用调用和复制/恢复有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆