在下面的代码#3和#4中打印“int i”的相同地址
谁能描述一下这是如何工作的?
它发生在一些 g++ 中,而不是在 vc++ 中,clang
#include <iostream>
int i = 0;
int main()
{
std::cout << "#1: " << &i << std::endl;
{
int i;
std::cout << "#2: " << &i << std::endl;
{
int i;
std::cout << "#3: " << &i << std::endl;
}
{
int i;
std::cout << "#4: " << &i << std::endl;
{
int i;
std::cout << "#5: " << &i << std::endl;
}
}
}
}
如果我运行上面的代码,结果如下
#1: 0x601194
#2: 0x7ffc027b5154
#3: 0x7ffc027b515c
#4: 0x7ffc027b5158
#5: 0x7ffc027b515c
最佳答案
Could anyone describe how this works?
变量被销毁后(对于自动存储变量,它会在其 block 结束时发生),其内存可以再次重用。因此,您所看到的情况 - 案例 #3 中的 i
会被销毁,因为它的 block 终止,并且稍后会再次重用该内存(在这种情况下,#5 中的 i
会重用相同的内存)。
关于不同 block 作用域中的C++变量具有相同的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59484364/