使用参数初始化局部静态

Initialising a local static with an argument

鉴于 C++ Primer 对局部静态对象的描述:

It can be useful to have a local variable whose lifetime continues across calls to the function. We obtain such objects by defining a local variable as static. Each local static object is initialized before the first time execution passes through the object’s definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates.

我惊讶地发现以下代码编译良好且输出合理:

#include <iostream>
using namespace std;

void test(int x){

    static int y = x;
    cout << y;

}

int main(){

    test(2);
    test(5);
    test(6);

}

通过这样的描述,似乎使用函数参数初始化是不可能的或没有多大意义,它如何在执行通过函数之前初始化 y,它怎么知道 x是了吗?这是 C++ Primer 的过度简化还是我的程序可能存在编译器无法检测的错误?

对于那些想知道为什么我可能会尝试使用参数初始化静态变量的人,我试图创建一个使用 default_random_engine 到 return 提供范围内的随机整数的函数它被调用的时间(因此需要 static 因此对象不会被破坏)作为 C++ Primer 的另一个练习的一部分:

unsigned randomUns(unsigned minV, unsigned maxV, default_random_engine::result_type seed = 0){

    static default_random_engine e(seed);
    static uniform_int_distribution<unsigned> u(minV, maxV);

    return u(e);
}

"before" 这个词由您的来源选择不当。 C++ 标准描述了具有静态存储持续时间的块作用域变量的初始化,如下所示 [stmt.dcl]/4:

Dynamic initialization of a block-scope variable with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

因此您的变量 y 在您第一次调用 test 时初始化。