de*******@gmail.com wrote:
I have a question for you C++ gurus. Let's say I have a class
singleton class such as:
class singleton
{
.
.
public:
singleton* getInstance();
private:
static singleton* __instance;
.
.
}
singeton.cpp:
singleton* singleton::__instance;
singleton* getInstance()
{
if (__instance==null) {
__instance = new singleton;
}
return __instance;
}
recommendation:
make instance a static variable inside getInstance(). That will provide
a cleaner way of ensuring initialization.
Also, and this is important, your entire example is undefined behavior.
The standard reserves all identifiers containing a double-underscore
regardless of scope to the implementation (see 17.4.3.1.2).
So try:
class singleton
{
public:
// all other member functions redacted for clarity
static singleton* getInstance();
};
singleton* singleton::getInstance()
{
// of course, you'll need appropriate threading safeguards here
static singleton* instance = 0;
if (!instance)
instance = new singleton;
return instance;
}
In addition, Alexandrescu's "Modern C++ Design" will tell you more than
you ever wanted to know about Singleton implementation.