On Jul 24, 1:11 am, Juha Nieminen <nos...@thanks. invalidwrote:
Puppet_Sock wrote:
On Jul 22, 7:35 am, Rajesh <mailtosraj...@ gmail.comwrote:
I read Global Object's constructor will be called before main()
function;
In which situation it can be really helpful? Is it good
practice use Global object and its constructor ?
For a discussion of when to use globals, and how to reduce
them, and why to reduce them, see _Code Complete (2nd Edition)_
by Steve McConnell. I have found this to be an excellent book.
(Few typos, but eh? What are you going to do?)
It's not necessary for the object to be global. It's enough
for it to be inside a namespace (eg. a nameless one).
The question is what he means by "global". The only use of
"global" in the standard (I think) is in the "global namespace";
the "outermost declarative region of a translation unit". It's
a namespace scope. Which means in fact that it is a scope, and
not an object lifetime (although object lifetime is in some
cases dependent upon the scope in which the object is defined).
And of course, if he's using global in this sense, then there
are a lot more objects which will be constructed before main.
(Except that the word he wants is probably initialized, rather
than constructed.)
The rule (the actual rule, not the formal one spelled out in the
standard) is that objects with static lifetime and non-local
scope are constructed either before main, or in the case of
dynamically loaded objects, before returning from dlopen or its
Windows equivalent. An object has static lifetime if:
-- it is defined at namespace scope, or
-- it is declared static (regardless of scope).
(Again, this is not the exact wording of the standard, but is, I
think, a fairly accurate summary.)
For example std::cout is constructed before main() is called.
std::cout and company are very special cases, in that the
standard places some additional constraints on them. (Among
other things, they are never destructed.)
--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34