Re: singleton
On Mar 25, 3:26 am, Ian Collins <ian-n...@hotmail.com> wrote:
thomas wrote:
hi guys,
-----code-----
class A{
private:
A(){}
public:
static A *getInstance(){
static A *a = new A(); //-------L1----
return a;
}
};
-----code-----
I use the static keyword to declare a static instance A,
I wonder if getInstance() is called multiple times, will L1 be
executed multiple times?
No, function static variables are initialised once when the function is
first called.
More correctly, when control flow first encounters the
declaration. No difference here, but if there were code before
the declaration, it could throw. (And of course, they're not
"function static variables", but "block scope static variables";
they can occur in an if, for example.)
You could also write
static A *getInstance(){
static A a ;
return &a;
}
Note that neither are necessarily thread-safe.
Also (just for completeness' sake), the variable is only
considered initialized once the complete initialization has
finished. If in one of the above, the constructor of A throws
an exception, it will be called again the next time the function
is called.
--
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