參考通話與複印/恢復之間的結果有什麼區別?參考通話與複印/恢復之間的區別
背景:我目前正在學習分佈式系統。關於遠程過程調用的參考參數的傳遞,本書指出:「引用調用已被複制/恢復取代,儘管這並不總是相同的,但它足夠好」。我理解如何通過引用和複製/恢復來調用原則上的工作,但我沒有看到結果的差異可能在哪裏?
參考通話與複印/恢復之間的結果有什麼區別?參考通話與複印/恢復之間的區別
背景:我目前正在學習分佈式系統。關於遠程過程調用的參考參數的傳遞,本書指出:「引用調用已被複制/恢復取代,儘管這並不總是相同的,但它足夠好」。我理解如何通過引用和複製/恢復來調用原則上的工作,但我沒有看到結果的差異可能在哪裏?
取自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