Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"What kind of things require this technique?"</p> <p>Point of fact: none.</p> <p>However, there are a lot of useful things you might WANT to do before main for a variety of reasons. For just one practical example, say you have an abstract factory that builds doohickies. You could make sure to build the factory instance, assign it to some special area, and then register the various concrete doohickies to it...yes, you can do that.</p> <p>On the other hand, if you implement the factory as a singleton and use the facts of global value initialization to "trick" the implementation into registering concrete doohickies before main starts you gain several benefits with very few costs (the fact of using singletons, basically a non-issue here, is pretty much the only one).</p> <p>For example you:</p> <ol> <li><p>Don't have to maintain a list of registrations that all must be explicitly called. In fact, you can even declare and define an entire class in private scope, out of sight of anyone, and have it available for use when the program starts.</p></li> <li><p>main() doesn't have to do a bunch of crap with a bunch of objects it doesn't care about.</p></li> </ol> <p>So, none of this is actually <em>necessary</em>. However, you can reduce coupling and maintenance issues if you leverage the fact that globals are initialized before main begins.</p> <p>Edit:</p> <p>Should note here that I've since learned that this isn't guaranteed by the language. C++ only guarantees that <em>zero</em> or <em>constant</em> initialization happens before main. What I talk about in this answer is <em>dynamic</em> initialization. This C++ guarantees happens before the first use of the variable, much like function-local static variables.</p> <p>Every compiler though seems to do dynamic initialization before main. I thought I ran into one once that did not but I believe the source of the issue was something else.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload