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:
static Singleton * instance() {
if(pSingleton==NULL)
pSingleton = new Singleton;
return pSingleton;
}
// ....
};
Singleton * Singleton:Singleton;
The other is to use a function static (also known as Meyer's
singleton)
class Singleton {
public:
static 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:
static Singleton& instance() {
return s;
}
// ....
};
Singleton Singleton::s;
It is interesting that a static member of itself (Singleton) is
declared inside
the Singleton class. I tested the code in linux, and g++
compiled it successfully.
My question is: How could this happen? How could a class have a member
of the type of itself? This is obviously not valid if there is no
keyword static. However, what features of the keyword
"static" make this feasible?
Thank you for any comments.
is
to use a static pointer
class Singleton {
static Singleton * pSingleton;
public:
static Singleton * instance() {
if(pSingleton==NULL)
pSingleton = new Singleton;
return pSingleton;
}
// ....
};
Singleton * Singleton:Singleton;
The other is to use a function static (also known as Meyer's
singleton)
class Singleton {
public:
static 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:
static Singleton& instance() {
return s;
}
// ....
};
Singleton Singleton::s;
It is interesting that a static member of itself (Singleton) is
declared inside
the Singleton class. I tested the code in linux, and g++
compiled it successfully.
My question is: How could this happen? How could a class have a member
of the type of itself? This is obviously not valid if there is no
keyword static. However, what features of the keyword
"static" make this feasible?
Thank you for any comments.