------- Comment #9 from broeni at osb-systems dot com  2006-02-07 12:52 -------
Obviously the behavior of the test program is undefined.
The following is the reply from Alberto Ganesh Barbati in c.l.c++.m

Apart from the fact that you need to include <ostream> in order to be
able to write on std::cout, yes: it's well defined. However, its
behaviour is unspecified. See below.

> In particular: Does the standard guarantee that std::cout is
> initialized before the constant `cInt'?

No, the standard does not guarantee that (although it non-normatively
encourages implementations to do it). According to ยง27.3/2: "The objects
[std::cin, std::cout, etc.] are constructed, and the associations are
established at some time prior to or during first time an object of
class ios_base::Init is constructed, and in any case before the body of
main begins execution."

So in order to ensure that the program behave as expected, you need to
construct a variable of type ios_base::Init before using std::cout. You
can either use a global variable like this:

int mkCint();
std::ios_base::Init gInitIostreams;
const int cInt = mkCint();

or use a local variable in function mkCint():

int mkCint()
{
     static std::ios_base::Init initIostreams;
     std::cout << "mkCint()" << std::endl;
     return 2;
}

Comment:
While the use of a global variable works fine for the reduced test #2 the
originally posted code (#1) only works with a local std::ios_base::Init in
mkCint() because of the undefined initialization order of globals.

The reply of James Kanze confirms the undefined behavior:
> Is the following program well defined?
> In particular: Does the standard guarantee that std::cout is
> initialized before the constant `cInt'?

No.

With the classical implementation of <iostream.h>, it was
guaranteed IF your code included <iostream.h> before defining
cInt.  Many (most?, all?) current implementations of <iostream>
also provide this guarantee, but the standard doesn't require
it.


-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26123

Reply via email to