C++ Singelton
Here is an example of a singelton class. Note the private constructor.
---------------------------------------------------------
class Singleton{
public:
int myInt;
static Singleton* getInstance();
protected:
Singleton();
private:
static Singleton* instance;
};
Singleton::Singleton(){}
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance(){
if(instance ==0)
instance = new Singleton();
return instance;
}
---------------------------------------------------------
Here is a wrapper class that demonstrats that all instances of
the singelton class are really shared instances of one.
(when all is one and one is all, --wow man thats deep)
---------------------------------------------------------
int main(){
std::cout<<"main:START\n";
Singleton* one = Singleton::getInstance();
Singleton* two = Singleton::getInstance();
Singleton* three = Singleton::getInstance();
one->myInt = 999;
std::cout<<"one: " << one->myInt << std::endl;
std::cout<<"two: " << two->myInt << std::endl;
std::cout<<"three: " <myInt << std::endl;
std::cout<<"main:END\n";
return 0;
}
-----------------------------------------------------------
here is the tar with these two files in it.
C++_Singelton