不同块作用域中的 C++ 变量具有相同的地址
c++ variables in different block scopes has same addresses
在下面的代码 #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?
变量被销毁后(对于自动存储变量,它发生在它们的块结束时)它的内存可以再次重用。所以你在那里看到的 - i
在案例 #3 中被破坏,因为它的块终止并且该内存稍后再次重用(在这种情况下,碰巧来自 #5 的 i
重用相同的内存)。
在下面的代码 #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?
变量被销毁后(对于自动存储变量,它发生在它们的块结束时)它的内存可以再次重用。所以你在那里看到的 - i
在案例 #3 中被破坏,因为它的块终止并且该内存稍后再次重用(在这种情况下,碰巧来自 #5 的 i
重用相同的内存)。