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