Re: Could this class be treated as Singleton class
Raman wrote:
Hi All,
I am new to the c++ programming.... lately I came to know about
singleton class( and various method to create one e.g making ctor
private and exposing an other function to create the only instance).
But I want to know ...can the following class be treated as
singleton ...If not then why ?
No, the class in not an implementation of the Singleton pattern.
There is a very fundamental difference between a class that can only
have one instance, ever, and a class that can have multiple instances,
but each instance is initialised to the value of the first one.
It is the second kind of class that you have created here.
#include<iostream>
using namespace std;
class temp{
static int count;
int test;
static void *ptr;
public:
temp(int t){
if(count==0) {
count++;
test=t;
ptr=(void *)this;/***Save the 1st instance**/
}
else {
*this=*(temp *)ptr;/***After that return the 1st instance
created----I am not sure what exactly is happening here */
What happens here is that you assign the value of the first (saved)
instance to the current instance.
I think this invokes Undefined Behaviour, because you are assigning to
an object that is still under construction.
}
}
~temp(){ /***I think, no need of delete ptr ass it will be done by
compiler automatically */
You should indeed not invoke delete on ptr, but it would be wise to
cleanup after yourself.
if (this == ptr)
{
count--;
ptr = NULL;
}
}
void printVal(){
cout<<"\n Val="<<test<<endl;
}
How about adding some extra members:
void setVal(int t)
{
test = t;
}
int getVal()
{
return test;
}
};
int temp::count=0;
void * temp::ptr=NULL;
int main()
{
temp t(10);
t.printVal();
temp t1(15);
t1.printVal(); /**both t and t1 contains 10 in the private data
member temp::test */
t.setVal(12);
t1.setVal(42);
t.printVal();
t1.printVal(); /** What do they print now? For a true singleton, it
would be the same */
assert(t.getVal() == t1.getVal()); /* The assertion should hold for a
singleton */
}
Thanks All,
Raman Chalotra
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]