Static Variables in C++: How Bad Can They Get?

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 -
  1. static changes the linkage or storage class of an identifier, which affects visibility and storage region.
  2. Aside from visibility, a global variable and a static global variable are otherwise the same.
  3. For C++ class members, static has 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
2
3
libc++abi: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
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
2
3
4
5
// env.h
static rwlock static_lock;

// env.cpp
rwlock static_lock;

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
2
3
4
static rwlock& GetLock() {
static rwlock lock;
return lock;
}

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
2
3
4
5
6
7
8
9
10
11
12
13
if ( obj_guard.first_byte == 0 ) {
if ( __cxa_guard_acquire(&obj_guard) ) {
try {
... initialize the object ...;
}
catch (...) {
__cxa_guard_abort(&obj_guard);
throw;
}
... queue object destructor with __cxa_atexit() ...;
__cxa_guard_release(&obj_guard);
}
}

You can also inspect the assembly for GetLock and see that the logic is basically the same.

05

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// CppClass
struct CppClass {
int age;
};

// oc
static pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;

static NSObject *obj = [[NSObject alloc] init];

static NSString *str = @"oc_str";

// c
static char *c_str = "c_str";

static int num1 {123};

static int num2 {num1};

// cpp
static CppClass cppObj;

static std::string cpp_str = "123";

static std::vector<int> vec = {1,2,3};

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, __data and does not need a runtime __cxx_global_var_init.

The demo shows two different initialization paths:

  1. The unhighlighted lines are all values that can be determined at compile time, so they do not trigger __cxx_global_var_init.
  2. The highlighted lines require runtime construction because the value cannot be determined during compilation, so the compiler emits ___cxx_global_var_init.xxx functions and calls them at runtime. The only missing one is CppClass, which is surprising.
1
2
3
4
5
➜  test.app nm test | grep cxx_global
0000000100004230 t ___**cxx_global**_var_init
0000000100004250 t ___**cxx_global**_var_init.2
0000000100004290 t ___**cxx_global**_var_init.4
0000000100004320 t ___**cxx_global**_var_init.66

A Few Notes

Here is a more detailed explanation of initializing a static variable from a function return value:

  1. obj depends on the return value of [[NSObject alloc] init], which clearly cannot be known at compile time.
  2. cpp_str looks simple because it only stores "123", but it still needs to call the std::string constructor. Static Variables in C++: How Bad Can They Get?: A Few Notes (figure 2)
  3. vec looks simple too because it is just {1,2,3}, but it still depends on the std::vector constructor. You can see that {1,2,3} is first converted into std::initializer_list, and then passed to std::vector. Static Variables in C++: How Bad Can They Get?: A Few Notes (figure 3)

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
2
3
4
struct CppClass {
std::string name;
int age;
};

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 T is trivial if all of the following is true:

  • The constructor is not user-provided.
  • T has no virtual member functions.
  • T has no virtual base classes.
  • Every direct base of T has 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
2
3
// code
bool ret = std::is_trivially_constructible<CppClass>::value;
std::cout << ret << std::endl;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// add user-provided construction
struct CppClass {
CppClass(){}
int age;
};

// add virtual method
struct CppClass {
virtual void test(){}
int age;
};

// add virtual base class
struct Base {
};
struct CppClass : virtual Base {
int age;
};

// add non-static member of class type who has no trivial default constructor
struct CppClass {
std::string name;
int age;
};

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 T is trivial if all of the following is true:

  • it is not user-provided;
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type member of T is 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
2
3
4
5
6
7
8
9
10
11
12
13
struct CppClass {
CppClass() {
std::cout << "CppClass Construction called" << std::endl;
}
CppClass(const CppClass& cc) {
std::cout << "CppClass Copy Construction called" << std::endl;
}
CppClass(CppClass&& cc) {
std::cout << "CppClass Move Construction called" << std::endl;
}
std::string name;
int age;
};

Then define two static variables:

1
2
static CppClass cppObj = CppClass();
static CppClass cppObj2 {CppClass()};

The output is:

1
2
CppClass Construction called
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
2
3
4
static NSObject *obj = [[NSObject alloc] init];
static int num2 {num1};
static std::string cpp_str = "123";
static std::vector<int> vec = {1,2,3};

For the four static variables above, if you assign values to them early inside +load:

1
2
3
4
5
6
+ (void)load {
obj = [[MyObject alloc] init];
num2 = 456;
cpp_str = "cpp_str_load";
vec = {4,5,6};
}

Then printing them again in viewDidLoad gives:

1
2
3
4
obj = <NSObject: 0x600002dcc010>
num2 = 123
cpp_str = "123"
vec = [1 2 3 ]

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:

Text
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
2
3
4
5
@implementation MMKV (Extension)
+ (void)load {
[MMKV initializeMMKV:nil];
}
@end

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
2
3
4
5
CPP_Exception std::_1: system_error
Thread 10 name: null

0 libc++.1.dylib std::_1:__throw_system_errorint, char const*) (in libct+. 1.dylib)
1 libct+.1.dylib std::__ 1:mutex::lock() (in libc++.1.dylib)

The crash happened at the line shown below. The code was trying to access the lock, but the lock was no longer valid.

1
2
3
4
5
6
7
8
template <typename Derived, bool ThreadSafe = true>
class ServiceFactory {
public:
static rwlock& GetLock() {
static rwlock lock;
return lock;
}
...

By observing the stack, I found an _exit call on another thread, which meant the process was exiting:

1
2
3
4
5
6
7
8
9
10
11
9   libsystem_c.dylib        _cxa_finalize_ranges (in libsystem_c.dylib)
10 libsystem_c.dylib _exit (in libsystem_c.dylib)
11 NewsInHouse _46+[FTAutoExit autoExitWhenReceiveNotification:]_block_invoke_2 (in NewsInHouse) FTAutoExit.m:18
12 libdispatch.dylib _dispatch_client_callout (in libdispatch.dylib)
13 libdispatch.dylib _dispatch_continuation_pop$VARIANT$mp (in libdispatch.dylib)
14 libdispatch.dylib _dispatch_source_invoke$VARIANT$mp (in libdispatch.dylib)
15 libdispatch.dylib _dispatch_queue_override_invoke (in libdispatch.dylib)
16 libdispatch.dylib _dispatch_root_queue_drain (in libdispatch.dylib)
17 libdispatch.dylib _dispatch_worker_thread2 (in libdispatch.dylib)
18 libsystem_pthread.dylib _pthread_wąthread (in libsystem_pthread.dylib)
19 libsystem_pthread.dylib _start_wąthread (in libsystem_pthread.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
2
3
4
5
s.xcconfig = {
"CLANG_CXX_LANGUAGE_STANDARD" => "c++14",
"CLANG_CXX_LIBRARY" => "libc++",
"OTHER_CPLUSPLUSFLAGS" => "-fno-c++-static-destructors",
}

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
2
3
4
static rwlock& GetLock() {
static rwlock *lock_ptr = new rwlock();
return *lock_ptr;
}

The Google way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// https://chromium.googlesource.com/chromium/src/base/+/master/no_destructor.h
template <typename T, typename O = std::nullptr_t>
class NoDestructor {
public:
template <typename... Args>
explicit NoDestructor(Args&&... args) {
new (storage_) T(std::forward<Args>(args)...);
}
explicit NoDestructor(const T& x) { new (storage_) T(x); }
explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); }
NoDestructor(const NoDestructor&) = delete;
NoDestructor& operator=(const NoDestructor&) = delete;
~NoDestructor() = default;
const T& operator*() const { return *get(); }
T& operator*() { return *get(); }
const T* operator->() const { return get(); }
T* operator->() { return get(); }
const T* get() const { return reinterpret_cast<const T*>(storage_); }
T* get() { return reinterpret_cast<T*>(storage_); }
private:
alignas(T) char storage_[sizeof(T)];
};
1
2
3
4
static rwlock& GetLock() {
static NoDestructor<rwlock> lock_wrap;
return *lock_wrap;
}

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

  1. By definition, NoDestructor does 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 of NoDestructor is trivial. Nothing needs to run, and the process memory will be reclaimed on exit anyway.
1
2
3
4
5
6
// code
bool ret = std::is_trivially_destructible<NoDestructor<rwlock>>::value;
std::cout << ret << std::endl;

// result
1
  1. The constructors of NoDestructor use placement new to construct T directly inside storage_. Because the wrapper itself has a trivial destructor and never explicitly invokes T::~T(), the contained rwlock remains 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:

  1. 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.
  2. 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.
  3. Avoid using function return values to initialize static variables.
  4. Avoid static destructors whenever possible, because destruction may involve multithreaded races and can crash.
  5. Avoid assigning to static variables inside +load, because values may later be overwritten.
  6. Avoid triggering static-variable access inside +load, because the static variable may not be initialized yet.

References

  1. C++ Static Variable Cross-Platform and Thread-Safety Analysis
  2. C++ Static Variable Initialization Order
  3. Research Global Variables Destruction Behavior in C++
  4. cxa_guard.cxx - Apple Open Source
  5. Default constructor - cppreference
  6. Copy assignment operator - cppreference
  7. Trivial destructor - cppreference
  8. Google C++ Style Guide - Static and Global Variables
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Static Variables in C++: How Bad Can They Get?

Author:lingyun

Published:2022-08-30 23:06

Updated:2026-10-07 00:00

Original link:https://tsuijunxi.github.io/en/2022/08/30/how-bad-can-static-variables-get/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.