Re: singleton initialization
On May 16, 5:48 pm, Fei Liu <fei...@aepnetworks.com> wrote:
Alf P. Steinbach wrote:
* Fei Liu:
Eric wrote:
class CTestClass
{
public:
static CTestClass& instance()
{
static CTestClass* m_instance = new CTestClass;
This doesn't make sense. How can the compiler create this object at
compile time?
The object is created at run time.
Change this to:
static CTestClass& instance()
{
static CTestClass* m_instance;
if(!m_instance) m_instance = new CTestClass;
return m_instance;
}
This merely replicates the code generated by the compiler for the
original, but in a more verbose and possibly less efficient way.
See ?6.7/4, "is initialized the first time control passes through its
declaration".
Ah, so this is the C++ way of doing it...I may be wrong, but in C at
least for plain old datatype, function static variable initialization
happens at compile time.
Sort of. C doesn't actually say when the initialization occurs,
except to require that it occur before the variable first
becomes usable. Since it only allows constant expressions in
the initializers, there's no way a conforming program can find
out when the initialization actually occurs.
C++ has the same concept: if the type has a trivial constructor,
and it initialized with a constant expression, the
initialization is said to be static, and all that is required is
that it occur before the first time the variable can possibly be
used---in all of the implementations I know of, the initialized
object is laid out by the compiler are part of the binary image,
at compile time. If the constructor isn't trivial, however,
some code must be executed, and it suddenly because possible for
a program to know when it is executed. So C++ defined a precise
moment for this.
--
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
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]