Vinícius
Vinícius

Reputation: 15746

Do I ever have to check for a pointer validity on this method?

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?

Upvotes: 1

Views: 161

Answers (3)

akton
akton

Reputation: 14386

Adding a check for the pointer is unlikely to cause significant performance degradation but should be unnecessary. Add it if it will make you feel better. However, I would be more concerned about buffer overflows, memory leaks and other more likely issues than whether the static keyword is implemented by the compiler correctly.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254621

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 obj might 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.

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308392

The function will always return a pointer to an object that exists. The only danger is if the object itself is invalid, and this should have been indicated by a throw from the object constructor. In your case you do not catch an exception from the constructor so the program should halt in that case, otherwise it should be good to go.

Checking for NULL is pointless because you always return a valid address.

Upvotes: 2

Related Questions