Background
In C++, the construction and destruction order of static variables across translation units is undefined, and it can even change from build to build. That leads to a lot of hard-to-predict bugs. If you put C++ code into an iOS project, the call timing can introduce another layer of trouble, which makes things even worse. This article summarizes a few static-variable issues I have run into before.
Within the same translation unit, the order is clear: static initialization happens before dynamic initialization, initialization follows declaration order, and destruction happens in reverse order. Across translation units, the order of initialization and destruction is unspecified.
Note: the experiments in this article were done with C++14.
What static Means
Before going further, let us revisit the meaning of
static in C-family languages, mainly in OC, C, and C++.
| qualified object | language | storage | visibility | initialization time |
|---|---|---|---|---|
| static global variable | OC/C | Data | file-local | before main |
| static local variable | OC/C | Data | visible inside the function or block | first use |
| static function | OC/C | Text | file-local | - |
| static data member | C++ | Data | visibility is expressed with public/protected/private | before main |
| static member function | C++ | Text | visibility is expressed with public/protected/private | - |
staticchanges the linkage or storage class of an identifier, which affects visibility and storage region.- Aside from visibility, a global variable and a static global variable are otherwise the same.
- For C++ class members,
statichas a different meaning and does not hide symbols.
Crash When Accessed Before Initialization
Static functions and static member functions have no initialization issue, so the main concern here is static variables.
The Trigger
I recently ran into this crash:
1 | libc++abi: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument |
After debugging, I found that a +load path eventually
reached a C++ static variable, but that variable had not been
initialized yet.
The static variable was implemented like this:
1 | // env.h |
Moving the Static Variable into Function Scope
+load may run before a C++ global has completed dynamic
initialization. A function-local static avoids that ordering dependency
by initializing the object on first use.
1 | static rwlock& GetLock() { |
This raises an immediate thread-safety question. Before C++11, concurrent first access could race. Since C++11, the standard requires function-local static initialization to be thread-safe. In the C++ ABI, the generated pattern looks like this:
1 | if ( obj_guard.first_byte == 0 ) { |
You can also inspect the assembly for GetLock and see
that the logic is basically the same.

More cxxabi details are available here: https://opensource.apple.com/source/libcppabi/libcppabi-14/
Initialization Types
So, how are the following static variables initialized?
1 | // CppClass |
In general:
- If the memory of a global variable is all zero, or if its initialization depends on runtime information, it goes into
__DATA, __bss.- If the initialization value can be determined at compile time, it goes into
__DATA, __dataand does not need a runtime__cxx_global_var_init.
The demo shows two different initialization paths:
- The unhighlighted lines are all values that can be determined at
compile time, so they do not trigger
__cxx_global_var_init. - The highlighted lines require runtime construction because the value
cannot be determined during compilation, so the compiler emits
___cxx_global_var_init.xxxfunctions and calls them at runtime. The only missing one isCppClass, which is surprising.
1 | ➜ test.app nm test | grep cxx_global |
A Few Notes
Here is a more detailed explanation of initializing a static variable from a function return value:
objdepends on the return value of[[NSObject alloc] init], which clearly cannot be known at compile time.cpp_strlooks simple because it only stores"123", but it still needs to call thestd::stringconstructor.
veclooks simple too because it is just{1,2,3}, but it still depends on thestd::vectorconstructor. You can see that{1,2,3}is first converted intostd::initializer_list, and then passed tostd::vector.
Trivial Default Constructor
What kind of C++ class static object will trigger
__cxx_global_var_init?
I tried adding one string member to
CppClass:
1 | struct CppClass { |
At that point, __cxx_global_var_init was triggered. That
made me suspect the key factor is whether the C++ constructor is
trivial.
https://en.cppreference.com/w/cpp/language/default_constructor
Trivial default constructor
The default constructor for class
Tis trivial if all of the following is true:
- The constructor is not user-provided.
Thas no virtual member functions.Thas no virtual base classes.- Every direct base of
Thas a trivial default constructor.- Every non-static member of class type has a trivial default constructor.
In practice, a trivial default constructor performs no work, so there is no point in calling it. A convenient way to test this is:
1 | // code |
1 | // add user-provided construction |
All four of the above cases trigger
__cxx_global_var_init, which strongly suggests the guess
was correct. In other words, for most C++ classes, satisfying the
trivial-constructor requirement is not easy.
Trivial Copy Assignment Operator
If we change the code to:
1 | static CppClass cppObj2 = CppClass(); |
This involves copy construction, so the same reasoning applies.
https://en.cppreference.com/w/cpp/language/copy_assignment
Trivial copy assignment operator
The copy assignment operator for class
Tis trivial if all of the following is true:
- it is not user-provided;
Thas no virtual member functions;Thas no virtual base classes;- the copy assignment operator selected for every direct base of
Tis trivial;- the copy assignment operator selected for every non-static class type member of
Tis trivial.
Extra Note
The copy constructor is not always called, because modern C++ has copy elision. I would like to thank Wu Yi for the hint, and then verify it:
1 | struct CppClass { |
Then define two static variables:
1 | static CppClass cppObj = CppClass(); |
The output is:
1 | CppClass Construction called |
The compiler really optimized it away, and only the constructor was called. The copy constructor was not called.
The official docs show that this behavior depends on the compiler:
https://en.cppreference.com/w/cpp/language/copy_elision
Copy elision is one of the optimizations that may change observable side-effects. Because some compilers do not perform copy elision in every situation where it is allowed, programs that rely on the side effects of copy/move constructors and destructors are not portable.
Value Overwrite
Besides crashes, static variables can also create a more subtle value-overwrite problem.
1 | static NSObject *obj = [[NSObject alloc] init]; |
For the four static variables above, if you assign values to them
early inside +load:
1 | + (void)load { |
Then printing them again in viewDidLoad gives:
1 | obj = <NSObject: 0x600002dcc010> |
They got overwritten again by __cxx_global_var_init.
I first noticed this while doing something unnecessarily fancy with MMKV. At that time, MMKV kept warning:
1 | MMKV not initialized properly, must call +initializeMMKV: in main thread before calling any other MMKV methods |
So I called [MMKV defaultMMKV] inside
+load:
1 | @implementation MMKV (Extension) |
As a result, g_basePath, which had already been
initialized in +load, was reset to nil, and
storage failed. (This only happened on iOS 10 devices. The details are
fuzzy now, but I may revisit it later.)
Destructor Crash
The Trigger
After fixing the earlier crash caused by uninitialized access, Fastbot found another static-variable crash:
1 | CPP_Exception std::_1: system_error |
The crash happened at the line shown below. The code was trying to access the lock, but the lock was no longer valid.
1 | template <typename Derived, bool ThreadSafe = true> |
By observing the stack, I found an _exit call on another
thread, which meant the process was exiting:
1 | 9 libsystem_c.dylib _cxa_finalize_ranges (in libsystem_c.dylib) |
So the static lock in use was likely destroyed by another thread during process shutdown.
Preventing Destruction
There are a few ways to solve this.
Disable static destructors with xcconfig
This is the recommended way; add it directly in the podspec:
1 | s.xcconfig = { |
Pointer approach
Declare the static variable as a pointer to a heap object. Since the static variable itself is just a pointer, it has no destructor.
1 | static rwlock& GetLock() { |
The Google way
1 | // https://chromium.googlesource.com/chromium/src/base/+/master/no_destructor.h |
1 | static rwlock& GetLock() { |
NoDestructor looks ordinary, so why does it solve the
destructor problem?
Before that, we need to understand Trivial Destructor:
https://en.cppreference.com/w/cpp/language/destructor#Trivial_destructor
Trivial destructor The destructor for class T is trivial if all of the following is true: The destructor is not user-provided The destructor is not virtual All direct base classes have trivial destructors All non-static data members of class type have trivial destructors
- By definition,
NoDestructordoes not provide a user-defined destructor (= default), it is not virtual, and it has no base class. Its only member,storage_, is not a class type, so the destructor ofNoDestructoris trivial. Nothing needs to run, and the process memory will be reclaimed on exit anyway.
1 | // code |
- The constructors of
NoDestructoruse placement new to constructTdirectly insidestorage_. Because the wrapper itself has a trivial destructor and never explicitly invokesT::~T(), the containedrwlockremains alive until the process exits.
Summary
This article summarized several static-variable pitfalls. They are subtle and difficult to debug, so it is worth understanding the mechanism behind them and avoiding dangerous patterns as much as possible:
- Avoid class-level global static variables whenever possible. Because construction and destruction order is uncertain, they can cause hard-to-find bugs. They can also affect startup time. If you must use them, prefer localizing the static variable. That is thread-safe and does not affect startup.
- Objects with static lifetime, including global variables, static
variables, static class members, and function statics, should ideally be
POD types such as
int,char,float, pointers, arrays, and structs made of PODs. Otherwise, make sure the class is trivial. - Avoid using function return values to initialize static variables.
- Avoid static destructors whenever possible, because destruction may involve multithreaded races and can crash.
- Avoid assigning to static variables inside
+load, because values may later be overwritten. - Avoid triggering static-variable access inside
+load, because the static variable may not be initialized yet.
References
- C++ Static Variable Cross-Platform and Thread-Safety Analysis
- C++ Static Variable Initialization Order
- Research Global Variables Destruction Behavior in C++
- cxa_guard.cxx - Apple Open Source
- Default constructor - cppreference
- Copy assignment operator - cppreference
- Trivial destructor - cppreference
- Google C++ Style Guide - Static and Global Variables