Skip to main content
GameDev.net gamedev.net
🔒 Locked

Singleton/C++ confused

Started by Wavewash Feb 18, 2005 at 10:56 PM 2 replies 2.7k views
Original Post
Wavewash
Wavewash
In the following:

// Declaration
class Singleton {
public: 
    static Singleton* Instance();
protected: 
    Singleton();
private:
    static Singleton* _instance;
}

// Implementation 
Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
    if (_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}

I am lost as to why they have not put implemntation for Instance() in a constructor Singleton(). Can you see a reason why they would avoid this? ~Wave
Xai
Xai
yes, you cannot "return an already created instance" in a constructor ...

Singleton *a, *b, *c, *d;

a = Instance(); // creates and gets "the one"
b = Instance(); // gets "the one"

a == b;

// but In your contructor based version, this would be different

c = new Singleton(); // creates a new one;
d = new Singleton(); // creates a differents new one;

c != d;
Xai
Xai
In case it wasn't clear, this is just because the constructor is a special function in C++ (as is the destructor) - the rules of C++ inheirently tie the concept of "contructor" to the concept of "instantiating a (NEW) instance of a class"
_goat
_goat
Actually, you can do it in the constructor, if you abide by:

int main()
{
new CSingleton;

a = CSingleton::GetSingleton();
b = CSingleton::GetSingleton();

return 0;
}


a == b;

This requires GetSingleton() to be a static function, but no matter.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.