不同块范围内的c ++变量具有相同的地址

问题描述 投票:2回答:1

在下面的代码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
c++ g++
1个回答
3
投票

谁能描述这是如何工作的?

变量被销毁后(对于自动存储变量,发生在其块结束时),其内存可以再次重用。这样一来,您会看到-情况#3的i在其块终止时被销毁,并且该内存稍后再次被重用(在这种情况下,碰巧#5的i重用了相同的内存)。

© www.soinside.com 2019 - 2024. All rights reserved.