Singletons are real handy for situations where only 1 object can be in usage.....you can impose a reference counting control, but if the count can only be 1, then here's a simpler method;
Code:
#include <iostream>
class foobar{
foobar(){}//Private...so only foobar::GetFoobar can use
foobar(const foobar&);//as above
public:
void Sing(){std::cout << "lalalalalala" << std::endl;}
static foobar& GetFoobar();//static member function to access singleton
};
foobar& foobar::GetFoobar(){
static foobar f;//this is created once on the first call to func
return f;//return reference
}
int main(){
//foobar a; \\cant create instance
foobar& b = foobar::GetFoobar();//can get and use reference
b.Sing();
foobar::GetFoobar().Sing();//Can get and use with single call
}
As you see, the constructors are all private.....so the only functions with access to create a foobar object are the static member functions of foobar itself.....so if you define a static member func that creates a static object, it will be created only once when the function is first called....you can then use that function and all it will do is return the reference to the single object.......quite nice and clean...