初始化静态变量 [英] initialization of the static variables

查看:163
本文介绍了初始化静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚读过,如果我想确定初始化顺序,最好使用一些函数,它将全局变量转换为本地(但仍然是静态的),我的问题,我需要保持一些标识符它告诉我,我的静态对象已经创建了(函数内的标识符,阻止我再次初始化静态对象)?因为我可以在不同的地方使用这个函数初始化,感谢提前任何帮助

I've just read that if I want to be sure about the initialization order it will be better to use some function which will turn global variable into local(but still static), my question, do I need to keep some identifier which tells me that my static object has already been created(the identifier inside function which prevent me from the intialization of the static object one more time) or not? cause I can use this function with initialization in different places, thanks in advance for any help

推荐答案

,函数作用域静态变量的初始化只发生一次:

As far as the standard is concerned, initialization of a function-scope static variable only happens once:

int *gettheint(bool set_to_four) {
    static int foo = 3; // only happens once, ever
    if (set_to_four) {
        foo = 4;   // happens as many times as the function is called with true
    }
    return &foo;
}

因此不需要 gettheint 检查 foo 是否已经初始化 - 该值不会被第二个 3 和随后的调用。

So there's no need for gettheint to check whether foo has already been initialized - the value won't be overwritten with 3 on the second and subsequent calls.

线程在工作中抛出一个扳手,超出了标准的范围。您可以检查您的线程实现的文档,但有可能是初始化的一次性在您的实现中不是线程安全的。这是 pthread_once 是用于,或等效的。或者,在多线程程序中,您可以在创建任何额外线程之前调用该函数。

Threads throw a spanner in the works, being outside the scope of the standard. You can check the documentation for your threading implementation, but chances are that the once-onliness of the initialization is not thread-safe in your implementation. That's what pthread_once is for, or equivalent. Alternatively in a multi-threaded program, you could call the function before creating any extra threads.

这篇关于初始化静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆