Valentin
Valentin

Reputation: 1158

Global statics lifetime? Can they crash your program?

Let's say you defined a couple file-level static objects:

//foo.cpp
static std::map<std::string, std::string> bar;
static MyCustomCompicatedClass baz;

Does c++ standard regulate their lifetime? When exactly will their destructors get called?

I've heard that global statics are never a good idea and may crash your program if their destructors get called after vcruntime gets loaded out of memory (on Windows, anyway). Is that true? Can someone share the details? What about other platforms?

Upvotes: 0

Views: 187

Answers (2)

R Sahu
R Sahu

Reputation: 206557

Global variables are initialized in two passes. The ones that can be const-initialized are initialed first. The ones that need dynamic initialization are initialized next.

The order in which global variables in two different compilation units are initialized is not specified. However, the variables in a given compilation unit are deterministic. They are initialized in the order in which they appear in the file.

All global variables are initialized before main is entered.

The standard guarantees that the destructors of those variables will be called in the opposite order of initialization.

A program may crash in the destructors if the program is buggy. If they are clean, your program should not crash.

Upvotes: 3

mrks
mrks

Reputation: 8333

Within one compilation unit, they are destroyed in the opposite order in which they were constructed.

Across units (i.e., in separate cpp files), their construction order (and thus their destruction order, too) is undefined (the "static initialization order fiasco") and all sorts of problems emerge.

Upvotes: 4

Related Questions