On Sep 25, 1:47 pm, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.comwrote:
Quote:
Consider the following program:
Quote:
#include <iostream>
Quote:
using namespace std;
Quote:
class Test
{
static Test t;
static Test init_Test( ) { return t; }
Test(const Test & rhs) { cout << "copy ctor" << endl; }
};
Quote:
Test Test::t = init_Test( );
Quote:
int main()
{
return 0;
}
Quote:
This program compiles fine under both g++ and VC++2005 Express
Edition and both produce the following same output
copy ctor
Which doesn't really surprise me, knowing roughly what the
compilers will generate.
Quote:
However consider the statement
Test Test::t = init_Test( );
Here init_Test( ) is called which returns the static member object
under construction which is 't'. I do not understand how we can
return an object which is still under construction.
You can't. It's undefined behavior.
Quote:
How is it accepted by the compiler ?
It's accepted by the compiler because the compiler is not
required to diagnose the error. It's accepted, in fact, because
the C++ is designed to allow separate compilation. There's
nothing in the line you cite which causes problems per se, given
that the compiler doesn't know what's in init_Test at that
point. (init_Test could return a local static, or even a newly
constructed object each time.) And there's nothing which causes
a problem per se in init_Test, since most uses of it would be
OK. It's only the combination of the two (this particular
implementation of init_Test(), used in this particular context)
which causes problems, and the language specification is
carefully designed so that the compiler is never required to
look into a function which is being called.
In practice, you're code works because the copy constructor
doesn't actually use the object it's copying. If it did, it
would find it uninitialized (or rather, zero initialized, since
this is a static object).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34