1

When reading the book Programming: Principles and Practices using C++, 2nd Edition I came along the following statement:

...what do you do if you really need a global variable (or constant) with a complicated initializer? A plausible example would be that we wanted a default value for a Date type we were providing for a library supporting business transactions:

const Date default_date(1970,1,1); // the default date is January 1, 1970

How would we know that default_date was never used before it was initialized? Basically, we can’t know, so we shouldn’t write that definition...

What got me curious about this line of code is the implied idea of using a global variable before its definition. What did the author (Bjarne Stroupstrup) exactly mean by using a global variable before its initialization? Of course, one could have declared the variable somewhere else. But that scenario is not mentioned.

Sam
  • 1,301
  • 1
  • 17
  • 26

1 Answers1

2

If there's another object declared in global scope, somewhere else, with a complex constructor, you have no practical means to specify the relative initialization order of these two objects in a portable manner. You can't expect, for either object, that the other object has been constructed, before it is referenced.

There's nothing inherently wrong with declaring global singleton objects, where they make sense, as long as it is fully understood that the relative initialization order of global objects in different translation units is not specified.

Community
  • 1
  • 1
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • If I get that correct this issue only arises if other global initializes reference this default_data variable? – Sam Nov 27 '16 at 01:40
  • 1
    Correct. All global objects are going to be initialized before `main()` gets invoked. That is the only guarantee (aside from the relative initialization order in the same translation unit). – Sam Varshavchik Nov 27 '16 at 01:42
  • 1
    If you can make the global `constexpr`, then you can avoid the possibility that it will be used prior to initialization. That may or may not be possible for `Date` depending upon its design and implementation. – Howard Hinnant Nov 27 '16 at 16:32