c++ - 使用参数初始化局部静态

标签 c++ c++11 static local

鉴于 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 每次返回提供范围内的随机整数作为 C++ Primer 的另一个练习的一部分调用(因此需要 static,这样对象就不会被破坏):

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);
}

最佳答案

“之前”这个词是你的来源选择的很差。 C++ 标准描述了具有静态存储持续时间的 block 作用域变量的初始化,如下所示 [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 时被初始化。

关于c++ - 使用参数初始化局部静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256960/

相关文章:

C++ 模板函数特化错误

c++ - 刷新缓冲区是什么意思?

c++ - 如何提取模板参数中传递的类型?

java - 有没有办法在 Java 中重新初始化静态类?

java - "overriding"main 在 Java 中有什么作用?

java - 如何访问非静态克隆的 arrayList 以在 Java 中的静态方法中使用

用于在编译时确定成员数量的 C++ 宏/元程序

c++ - C++中的临时问题

c++ - 如何在gdb中打印指针列表的内容?

c++ - 动态构建模板参数包