class A
{
private:
A(){};
~A(){};
public:
static A* GetInstance( void )
{
static A obj;
return& obj;
}
};
I was supposing if something bad happens would only happen at the first time, since the class constructor is only initialized the first time a call to GetInstance happens, I don’t know the great depths of C++ and I do not trust C++, so when I need a pointer to this class that will be used many times in a function I’m currently doing:
A* ptr = A::GetInstance();
if( ptr )
{
Checking for the pointer validity, I believe that the method returns the address where the value of obj is stored so that ptr will point to it, which I guess it can't fail.
Please observe that I’m not talking about a small application, I’m currently developing on a 500,000+ lines MMO server application that handles thousand of clients and has to stay opened for weeks without crashing, defensive programming is the least minimum required. Is it for sure, 100% safe to use ptr without checking its validity?
There is certainly no way that that function will ever return a null pointer, so there’s no point checking for that. It might make more sense to return a reference, to make it clear that it won’t be null.
However, there’s no guarantee that the function will always return a pointer to a valid object. If it’s called from the destructor of a static object, then
objmight already have been destroyed. This is one reason why globally accessible objects are a very bad idea, whether or not you wrap them up in the Singleton anti-pattern like this.