Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How can C++ avoid complex initialization of global objects

Shulou Source: shulou.com Published: 2022-06-01 19:12:10 10月01日 Update

This article mainly explains "C++ how to avoid complex initialization of global objects". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "C++ how to avoid complex initialization of global objects" together!

Reason

Complex initialization may result in undefined execution order.

Example

// file1.cextern const X x;const Y y = f(x); // read x; write y// file2.cextern const Y y;const X x = g(y); // read y; write x

Since x and y are in different translation (compilation) units, the order in which f() and g() are called is undefined; one of them accesses an uninitialized constant. This indicates that initialization order problems that occur with global (namespace-scoped) objects are not limited to global variables.

Translator's Note: This also affects the functions that use them.

Note:

In concurrent code, initialization order issues are particularly difficult to handle. In summary, the best option in general is to avoid global (namespace-scoped) objects. Enforcement

Flag initializers of globals that call non-constexpr functions

Marks global objects that call initialization of non-constant expression functions.

Constant expression functions may be evaluated at compile stage and therefore safe.

Flag initializers of globals that access extern objects

Marks global objects initialized with external variables.

External variables can be initialized in unpredictable ways.

Thank you for reading, the above is "C++ how to avoid complex initialization of global objects" content, after the study of this article, I believe that we have a deeper understanding of how to avoid complex initialization of global objects in C++, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Global object complexity complexity order function variable translator problem learning content constant case tag space scope expression compilation different difficult Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Redmi Microsoft Docker Shulou Information