Hi ppl
I have a doubt on singleton class. I am writing a program below
class singleton
{
private:
singleton(){};
public:
//way 1
static singleton instance()
{
static singleton s;
return s;
}
//way 2
static singleton* instance()
{
static singleton s;
return &s;
}
};
int main(int argc, char* argv[])
{
//If way1
singleton st1=singleton::instance();
singleton st2=singleton::instance();
printf("\n%08X",&st1);
printf("\n%08X",&st2);
//if way 2
singleton *st1=singleton::instance();
singleton *st2=singleton::instance();
printf("\n%08X",st1);
printf("\n%08X",st2);
return 0;
}
Now my doubts are as follows:
1. the address of st1 and st2 are different for way1
2. the output is correct in way2. The addresses outputted are equal.
So thats a correct implementation of singleton class.
3. I feel that in way1 the compiler should complain. Because its same
as:
singleton st1; //generates compiler error since call to
private CTOR
singleton st2; //generates compiler error since call to private
CTOR
st1=singleton::instance();
st2=singleton::instance();
printf("\n%08X",&st1);
printf("\n%08X",&st2);
But the compiler does not complain. I am using MS VC++ 6.0 compiler.
4. Even if the compiler understands me correctly for the 1st way, i
feel that the addresses should be printed out equal. This is because
the object made inside the static function is also declared static, so
only the 1st call to it will create an object and the rest of calls
wont.
Can someone comment on the 1st way. I know its wrong but i cannot
figure out a valid reason. The 2nd way is the correct way to create
singleton class in C++.
Thank you for your comments in advance