考虑以下代码 -
#include <iostream>
#include <stdio.h>
const int & retRef() {
return 6;
}
int main()
{
const int& k = retRef();
printf("Value: %d\n", k);
printf("Address: %p\n", &k);
printf("Value: %d\n", k);
return 0;
}
输出是 -
Value: 6
Address: 0x7ffd45bf544c
Value: 32692
为什么在打印变量的地址后值会改变k
?如果我用 替换该行const int& k = retRef()
,const int& k = 6;
则输出符合预期。
为什么会有这种不同的行为?提前致谢