Re: singleton
On Mar 25, 8:49 am, Ian Collins <ian-n...@hotmail.com> wrote:
Rahul wrote:
On Mar 25, 7:17 am, thomas <FreshTho...@gmail.com> 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?
generally a initialization sentence of static variable will
be executed only once, but I'm not sure what will the c++
compiler expand for L1.
make sure its thread safe too... you could consider using a
mutex or binary semaphore for the same...
For the same what? The implementation should guarantee the
static variable is initialised once only.
The standard guarantees that the variable is only initialized
once, unless, of course, the program has undefined behavior
elsewhere. The standard also considers a call to pthread_create
(or it's equivalent under Windows) undefined behavior, however,
so anytime threading is involved, you have to consider the
guarantees given by the implementation. As far as I know, g++
is the only compiler which guarantees "thread safety" for the
above, and it's implementation is defective on at least one
platform. So as a programmer, you do have to pay attention.
--
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