Re: About initializing non-local object
On May 17, 8:47 am, Jidilo <jid...@gmail.com> wrote:
On 16 mai, 19:10, Jidilo <jid...@gmail.com> wrote:
Like:
//file1.cpp
int g_var1 = 3;
//file2.cpp
extern int g_var1;
int g_var2 = g_var1;
No matter what the initialization order is, when g_var2 is
initialized, g_var1 will be in an initialized state.
In this case, the initialization order is defined. Static
initialization (g_var1) always takes place before dynamic
intialization (g_var2). To extend my previous example:
OK but what if:
extern int x1;
extern int x2;
int x1 = x2;
int x2 = x1;
?
That's all dynamic initialization, so first zero initialization
will set both to 0, then dynamic initialization will occur in
the declaration order (within any single file)
Still having question about this. I have try this:
class A {
public:
A(const A& a, const std::string& name) { cout << name << endl; }
};
file 1:
-------
extern A a2;
A a1(a2, "a1");
file 2:
-------
extern A a1;
A a2(a1, "a2");
And got no compilation error. In this case, what is the
behaviour ? is it well defined ?
It's defined behavior, but unspecified: both variables will
first be zero initialized, then one of the variable's
constructors will be called, then the other one. The first
constructor will see a zero initialized A const&.
You might try it, adding something to A so that you can see the
initialization, say:
class A
{
public:
A( A const& other, std::string const& name )
: myFirst( 1 )
, mySecond( other.myFirst )
{
std::cout << name << std::endl ;
}
int myFirst ;
int mySecond ;
} ;
Use this in the two files above, and try linking them in
different orders. After initialization, both objects will have
myFirst == 1, but one of them will have mySecond == 1, the other
== 0. Which one is not specified, but with most compilers,
you'll find that it will depend on the order the object files
are incorporated into the build. (In an unspecified way; you
can't reliably use this for controlling order of initialization,
even unportably.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34