赞
踩
If a function-scope static variable or a static data member with vague linkage (i.e., a static data member of a class template) is dynamically initialized, then there is an associated guard variable which is used to guarantee that construction occurs only once. The guard variable's name is mangled based on the mangling of the guarded object name. Thus, for function-scope static variables, if multiple instances of the function body are emitted (e.g., due to inlining), each function uses the same guard variable to ensure that the function-scope static is initialized only once. Similarly, if a static data member is instantiated in multiple object files, the initialization code in each object file will use the same guard variable to ensure that the static data member is initialized only once.
The size of the guard variable is 64 bits. The first byte (i.e. the byte at the address of the full variable) shall contain the value 0 prior to initialization of the associated variable, and 1 after initialization is complete. Usage of the other bytes of the guard variable is implementation-defined.
See Section 3.3.2 for the API for references to this guard variable.
if (obj_guard.first_byte == 0) { //zi如果obj_guard为0,表示还没有被初始化 if ( __cxa_guard_acquire (&obj_guard) ) { //zi获取锁,避免多线程初始化 try { ... initialize the object ...; } catch (...) { __cxa_guard_abort (&obj_guard); throw; } ... queue object destructor with __cxa_atexit() ...; __cxa_guard_release (&obj_guard); //zi释放锁 } }
上面的源代码分析可以参考:深入理解函数内静态局部变量初始化
"Returns 1 if the initialization is not yet complete......"、“Sets the first byte of the guard object to a non-zero value. This function extern "C" void __cxa_guard_release ( __int64_t *guard_object ) is called after initialization is complete.....”
(b)
“说说msvc的实现。编译器自动创建两个全局变量,一个指向静态局部变量的指针,一个布尔值,用于标记是否第一次使用。下面就很简单了,第一次进函数时创建对象,以后都直接使用该对象。”
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。