Static and global constructors

R

Richard Hayden

Hi,

I'm wondering if there is any order in the calling of global and static
member objects' constructors which occurs before a C++ program can run.
For example, what if I wish to use static member variable objects in a
global variable's constructor? I was thinking that perhaps C++
guarantees to construct all global variable objects first or all static
member variable objects first. Is this at all the case?

Thanks,

Richard Hayden.
 
G

Gregg

Hi,

I'm wondering if there is any order in the calling of global and static
member objects' constructors which occurs before a C++ program can run.
For example, what if I wish to use static member variable objects in a
global variable's constructor? I was thinking that perhaps C++
guarantees to construct all global variable objects first or all static
member variable objects first. Is this at all the case?

Thanks,

Richard Hayden.

Statics are constructed in the order in which they appear in each
translation unit (single compiled file and what it #includes). Order of
initialization between translation units is implementation defined. If
you need to be able to use global objects across translation units, you
either have to use a trick like "nifty counter" (google to find out what
it is) or use a singleton object that creates it on demand.

Gregg


Gregg
 
G

Gregg

Statics are constructed in the order in which they appear in each

By "order in which they appear", I meant "order in which the objects are
defined". The order they are declared is immaterial to construction order.

Gregg
 
P

Pete Becker

Gregg said:
What's the difference? Isn't a given implementation deterministic in this
regard?

The difference is that implementation defined means that a conforming
implementation must document what it does. Yes, it's deterministic, but
typically far too complex for anyone to want to try to figure out.
Objects in libraries are only linked when the linker determines that
they're needed; sometimes that requires multiple passes through the list
of libraries.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,949
Members
47,500
Latest member
ArianneJsb

Latest Threads

Top