| 1 |
.. title:: clang-tidy - bugprone-dynamic-static-initializers |
| 2 |
|
| 3 |
bugprone-dynamic-static-initializers |
| 4 |
==================================== |
| 5 |
|
| 6 |
Finds instances of static variables that are dynamically initialized |
| 7 |
in header files. |
| 8 |
|
| 9 |
This can pose problems in certain multithreaded contexts. For example, |
| 10 |
when disabling compiler generated synchronization instructions for |
| 11 |
static variables initialized at runtime (e.g. by ``-fno-threadsafe-statics``), even if a particular project |
| 12 |
takes the necessary precautions to prevent race conditions during |
| 13 |
initialization by providing their own synchronization, header files included from other projects may |
| 14 |
not. Therefore, such a check is helpful for ensuring that disabling |
| 15 |
compiler generated synchronization for static variable initialization will not cause |
| 16 |
problems. |
| 17 |
|
| 18 |
Consider the following code: |
| 19 |
|
| 20 |
.. code-block:: c |
| 21 |
|
| 22 |
int foo() { |
| 23 |
static int k = bar(); |
| 24 |
return k; |
| 25 |
} |
| 26 |
|
| 27 |
When synchronization of static initialization is disabled, if two threads both call `foo` for the first time, there is the possibility that `k` will be double initialized, creating a race condition. |