Topic: Is it guaranteed that a static Object is crated at startup time ? -


Author: Ole Reinartz <ole.reinartz@gmx.de>
Date: Thu, 2 May 2002 20:06:06 GMT
Raw View
Marco Siciliano wrote:

> Hi,
>
> i have implemented a singelton pattern using a  creator object:
> Is this save ?  Is it guaranteed, that this creator object is created at the
> program startup ?
>
> class FooCreator
> {
> public:
>     FooCreator()
>     {
>         Foo::instance = new Foo;
>     }
>
>     ~Foo()
>     {
>         delete Foo::instance;
>     }
> };
>
> static FooCreator creator;     // IS THIS OK ??????

Probably not: At least you should never define such a static object in a header
file. Several modules might include that header file and you might end up
having several instances of your static.
But It is guaranteed that the static FooCreator will be created before int
main() is called to.
But there is more: It may be that in your program other statics exist that
access your static at their creations. It may be that this happens at a time
when the FooCreator got not created yet.
There is an easy way to get around that and you even don"t need the FooCreator
anymore, but just this:

class Foo
{
public:
    static Foo & instance();

private:
   };

Foo & Foo::instance()
{
    static Foo instance;
    return instance;
}

This way your Foo singleton instance will be created the first time
Foo::instance() gets called to. It is not guaranteed that it exists before
main() gets executed, but it is guaranteed that it exists after someone called
for it.

Ole

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]