By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,928 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,928 IT Pros & Developers. It's quick & easy.

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

P: n/a
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?

Nov 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
VJ
Kavya wrote:
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
Nov 1 '06 #2

P: n/a

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.

Nov 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.