2
上下文的一點:我在測試編譯器的優化時使用引用(他們非常擅長它)。 在某些時候,我通過引用一個結構構造函數傳遞了兩個對象......而事情變得更加奇怪。我可以看到對結構體外的其中一個對象所做的更改,但不能看到其他對象。在對象中存儲引用產生更奇怪的結果
我想出了什麼,我的意思是說一個最小的工作例如:
//TwoInts has two references to int
//For whatever reason I can only see outside changes
//done to the int pointed by ref1 !
struct TwoInts{
int& ref1,ref2;
TwoInts(int& r1,int& r2):ref1(r1),ref2(r2){}
};
int foo(int select){
int a=0,b=0;
TwoInts two(a,b);
switch(select){
case 1:
a=1; //This line changes the output
return two.ref1; //Returns 1, ok
break;
case 2:
b=2; //This line DOESN'T change the output
return two.ref2; //Returns zero!
break;
}
}
生成的彙編與G ++使用-02
foo(int):
cmp edi, 1
je .L3
cmp edi, 2
jne .L9
xor eax, eax
ret
.L9:
rep ret
.L3:
mov eax, 1
ret
活生生的例子here
V5.4 - 如果我將1傳遞給foo,則代碼跳轉到.L3並返回1,以反映對a進行的更改;
- 但是如果我通過2到foo代碼跳到.L9和返回0,忽略至b作出的變化。
我不知道爲什麼會發生這種情況。對此有何想法?
[編輯] 當你一個人工作時,在圈子裏運行真的很容易。的確,ref2的類型只是int,而不是int &。謝謝你的回覆!
這是更好地保留每行一個聲明,因爲這樣的錯誤很容易。 – Galik
在'int&ref1中,ref2'' ref2'不是引用。 '&'適用於'ref1',而不是'int'。 –
哎喲,我真的很想念它。謝謝! – pdp11