访问静态超出范围未定义的行为吗?

Is accessing a static out of scope undefined behavior?

在与我的一位同事交谈时,他们说:

foo() {
    int *p;
    {
        int x = 5;
        p = &x;
    }
    int y = *p;
}

creates undefined behavior because lifetime rules and scope rules do not specify.

However:

foo() {
    int *p;
    {
        static int x = 5;
        p = &x;
    }
    int y = *p;
}

is not undefined! You end up with "indirect scoping" issues.

术语的使用听起来不正确。
我知道静态与范围无关。
第二种情况是否具有定义的行为?

是的,第二种情况具有明确定义的行为。 static 变量基本上是一个全局变量,其名称的范围限定在它声明的范围内。它在第一次进入范围时被初始化,然后它在程序的生命周期中一直存在。

所以当我们到达

int y = *p;

p 指向一个您无法再访问(无法返回到该代码)但仍然具有有效生命周期的变量。

引用标准[basic.stc.static]

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program

强调我的

第一种情况是未定义的,因为局部作用域 x 的生命周期结束于 } 并且在其生命周期结束后尝试引用它是未定义的行为。

引用自 here

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

所以在第二种情况下是的 x 在程序的整个生命周期中都存在。

因此定义了行为。