Is it simple way to create a singleton or is it wrong?

K

Kavya

I've seen codes for singletons in which people write =, copy
constructor, constructor in private section and have some kind of
static member function which returns instance of class. I was able to
understand that.
But today I came across this code which I saw in "Test Your C++ Skills"
by Yashwant Kanetkar. This looks even more simpler but like many other
questions in the book I am sure this must also be having some problems.

I modified the code to add standard headers and changed return type of
main to int.


#include<cstdlib>
#include<iostream>
using namespace std;

class sample{
private:
static int count;
public:
sample(){
if(1==count)
exit(0);
cout<<"Object created\n";
++count;
}
};
int sample::count=0;

int main(){

sample s1;
sample s2;
return 0;
}

Can someone say few points about this?
 
V

VJ

Kavya said:
I've seen codes for singletons in which people write =, copy
constructor, constructor in private section and have some kind of
static member function which returns instance of class. I was able to
understand that.
But today I came across this code which I saw in "Test Your C++ Skills"
by Yashwant Kanetkar. This looks even more simpler but like many other
questions in the book I am sure this must also be having some problems.

I modified the code to add standard headers and changed return type of
main to int.


#include<cstdlib>
#include<iostream>
using namespace std;

class sample{
private:
static int count;
public:
sample(){
if(1==count)
exit(0);
cout<<"Object created\n";
++count;
}
};
int sample::count=0;

int main(){

sample s1;
sample s2;
return 0;
}

Can someone say few points about this?

This is wrong, because:
1) the sample class has no method to get the only instance of the class
2) look at this snip of a code which will break your sample class:

[...]
{
sample a;
// do something if you like
}
[...]

Trying to make another sample object would exit the program


Check http://sourceforge.net/projects/loki-lib/ how it is done
 
D

dasjotre

The basic point of a singleton pattern is to limit
the number of instances of a class to 1.
The sample you presented does that but
in a thoroughly useless way.

For an in-depth discussion of a singleton
design I recommend reading
"The modern c++ design"
by Mr. Alexandrescu.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top