W
wizwx
There are two typical implementations of a singleton. The first one is
to use a static pointer
class Singleton {
static Singleton * pSingleton;
public:
Singleton * instance() {
if(pSingleton==NULL)
pSingleton = new Singleton;
return pSingleton;
}
// ....
};
Singleton * Singleton:Singleton;
The other is to use a function static
class Singleton {
public:
Singleton& instance() {
static _singleton;
return _singleton;
}
// ....
};
However I just noticed a third one from Bruce Eckel's "Thinking in C+
+" vol. 2, pp 620:
class Singleton {
static Singleton s;
public:
Singleton& instance() {
return s;
}
// ....
};
It is interesting that a static member of itself is declared inside
the Singleton class. I tested the code in linux, and g++ successfully
compiled it.
My question is: How should the compiler know how to allocate memory
for the static member of Singleton? Any features of the keyword
"static" make this feasible?
Thank you for any comments.
to use a static pointer
class Singleton {
static Singleton * pSingleton;
public:
Singleton * instance() {
if(pSingleton==NULL)
pSingleton = new Singleton;
return pSingleton;
}
// ....
};
Singleton * Singleton:Singleton;
The other is to use a function static
class Singleton {
public:
Singleton& instance() {
static _singleton;
return _singleton;
}
// ....
};
However I just noticed a third one from Bruce Eckel's "Thinking in C+
+" vol. 2, pp 620:
class Singleton {
static Singleton s;
public:
Singleton& instance() {
return s;
}
// ....
};
It is interesting that a static member of itself is declared inside
the Singleton class. I tested the code in linux, and g++ successfully
compiled it.
My question is: How should the compiler know how to allocate memory
for the static member of Singleton? Any features of the keyword
"static" make this feasible?
Thank you for any comments.