"Deming He" <de*******@worl dnet.att.net> wrote in message
news:gi******** ************@bg tnsc04-news.ops.worldn et.att.net...
Jumbo @uko2.co.uk> <pcr1000011<nos pam> wrote in message
news:10******** *******@news.mi nx.net.uk...
"Deming He" <de*******@worl dnet.att.net> wrote in message
news:mo******** ************@bg tnsc04-news.ops.worldn et.att.net... E. Robert Tisdale <E.************ **@jpl.nasa.gov > wrote in message
news:40******** ******@jpl.nasa .gov...
> Could somebody please help me with the definition of a singleton?
>
> > cat singleton.cc
> class {
> private:
> // representation
> int A;
> int B;
> public:
> file://functions
> const
> int& a(void) const { return A; }
> int& a(void) { return A; }
> const
> int& b(void) const { return B; }
> int& b(void) { return B; }
> } singleton;
>
Here you go...
class singleton{
enum {MAX_INSTANCE=1 };
static int num_of_instance s;
// representation
int A;
int B;
public:
// functions
const int& a(void) const { return A; }
int& a(void) { return A; }
const int& b(void) const { return B; }
int& b(void) { return B; }
static singleton* get_a_singleton _instance();
};
singleton* singleton::get_ a_singleton_ins tance()
{
if(num_of_insta nces<MAX_INSTAN CE){
++num_of_instan ces;
return new singleton;
}
else
return null;
}
int singleton::num_ of_instances = 0;
You can still create more than one of them i.e:
int main(){
singleton sg1;
singleton sg2;
return 0;
}
I don't believe this is a singleton.
Yeah, you're correct. Why not add a "private" default cstor for
"singleton" class?
Yes.
Something like this? :
#include <iostream>
class Singleton{
private:
friend class S;
Singleton(){std ::cout<<"Single ton constructor"<<' \n';}
~Singleton(){st d::cout<<"Singl eton destructor"<<'\ n';}
Singleton& operator=(const Singleton& rhs){}
Singleton(const Singleton& rhs){}
};
class S{
private:
static int count;
S(){}
public:
static int getCount(){retu rn count;}
static Singleton* CreateSingleton (){
if(!count){
count++;
return new Singleton;
}else return 0;
}
static ReleaseSingleto n(Singleton* p){
delete p;
count--;
}
};
int S::count = 0;
int main(){
Singleton* s1 = S::CreateSingle ton();
S::ReleaseSingl eton(s1);
s1=0;
std::cout<< "No of Singletons: " << S::getCount() << std::endl;
Singleton* s2 = S::CreateSingle ton();
Singleton* s3 = S::CreateSingle ton();
/*s3 is null*/
std::cout<< "No of Singletons: " << S::getCount() << std::endl;
S::ReleaseSingl eton(s2);
return 0;
}