[UE4]C++静态局部变量

void testFunc()
{
static int runCount = 0; // this only runs ONCE, even on
// subsequent calls to testFunc()!
cout << "Ran this function " << ++runCount << " times" << endl;
} // runCount stops being in scope, but does not die here

int main()
{
testFunc(); // says 1 time
testFunc(); // says 2 times!
}

C++ 局部静态初始化是线程安全的

对于基本数据类型而言,局部静态变量和全局变量一样都是在进入main之前初始化的,可以认为是线程安全的; 而对于自定义类型的局部静态变量(对象),编译器的做法是定义一个bool型的局部静态变量,初始化为false,然后在函数中进行判断,如果为假就进行对象的初始化操作,如果为真就直接返回对象,这样就不是线程安全的了,因为对象可能被初始化多次。可以做个测试:
1、基本数据类型
void fun(){
    static int a = 0x123456;
    cout << a << endl;
}
int b =0x111111;
int main(){
fun(); //在这里加断点:在内存中查看b的值,应该可以看到紧挨着就有a的值
    return 0;
}
2、自定义类型
class A{
    public:
        A(){
            cout << " A " <<endl;
        }
};

void fun(){
    static A a; // 在这里加断点,查看汇编代码,可以看到有一个比较命令,转换成伪代码应该是个if语句
}
int main(){
    fun(); //在这里加断点,此时fun函数还没有执行,A a仍然没有初始化, 因为如果a初始化了,控制台就会有输出
}

 

posted on 2018-03-22 15:47  一粒沙  阅读(959)  评论(0编辑  收藏  举报