一些上下文:我正在使用引用时测试编译器的优化(顺便说一句,它们非常擅长)。 在某些时候,我通过引用结构构造函数传递了两个对象......事情变得很奇怪。我可以看到对结构体外部的一个对象所做的更改,但看不到另一个对象。
我提供了一个最小的工作示例来说明我的意思:
//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;
}
}
使用 -O2 使用 g++ v5.4 生成汇编程序
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
-如果我将 1 传递给 foo,代码将跳转到 .L3 并返回 1,反射(reflect)对 a 所做的更改;
-但是如果我将 2 传递给 foo,代码就会跳转到 .L9 并返回 0,忽略对 b 所做的更改。
我不知道为什么会发生这种情况。对此有什么想法吗?
[编辑] 当你一个人工作的时候,真的很容易原地踏步。事实上,ref2 的类型只是 int,而不是 int&。谢谢各位的回复!
最佳答案
声明 ref1
和 ref2
的方式使 ref1
成为 int
引用,但 ref2
一个 int
值。
在结构中有两个引用的正确声明应该是:
int &ref1, &ref2;
关于c++ - 在对象中存储引用会产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258913/