Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Non-local static object vs local static object

Tags:

c++

Regarding the book "Effective C++" from Scot Meyers, and the 4th item: non-local static objects can be uninitialized before the are used (static in this case means "global", with static life). If you replace it with a local-static object, which is created inside a function that returns a reference to it, the object is then for sure initialized before use.

I always have a file with constants. I declare extern const int a; in an .hpp file and define it in the .cpp file. But can then the same thing happen? a can be uninitialized. Or not? Does the same rule apply for built-in types?

like image 785
Dusan Avatar asked Oct 30 '22 11:10

Dusan


1 Answers

Even though you can, it's not such a good idea to return references to "local-static" variables. The variable was (presumably) declared locally to reduce its scope to just the enclosing function, so attempting to increase its scope in this manner is rather hacky. You could make it a global variable and use something like std::call_once to guarantee it's initialized exactly once on first usage. Returning a mutable reference to a local-static object also raises thread-safety concerns because the function may no longer be re-entrant.

POD types with static storage duration are guaranteed to be zero-initialized. You can also initialize them with a constant expression and the language will guarantee they are initialized before any dynamic initialization takes place. Here's a similar question that may provide some additional insight.

like image 151
v1bri Avatar answered Nov 15 '22 07:11

v1bri