Singleton Problem

Recommended Posts

This is not the exact code which I saw in the book. But it used this logic to create a Singleton. I guess this is not right. What do you say?
#include <iostream>
using namespace std;
class a{
int x;
public:
a()
{
static count=0;
if(count > 0)
exit(0);
else
{
count++;
x=10;
}
}
};
int main(int argc, char *argv[])
{

a obj;
a obj2;
return EXIT_SUCCESS;
}



Share on other sites
http://www.gamedev.net/reference/articles/article1825.asp

Share on other sites
Quote:
 Original post by TEUTONBut it used this logic to create a Singleton. I guess this is not right. What do you say?

I agree. Singletons are illogical. [wink]

Share on other sites
Make count a static member of a and you'll get the behavior I assume you're looking for, but instead you should just forget the singleton exists.

Share on other sites
The only usefull use of the singleton pattern is in resolving problems with the initialization order of global and static objects.

In one compilation unit, you have some sort of global structure. Say, an std::map.
In another compilation unit, you have some sort of static that uses the global structure during construction, wether directly or through some global/static function somewhere.
Now, since the initialization order of statics and globals in different compilation units is undefined, this might work... or it might not. If the map is initialized first, it works. If not, it doesn't.
You can fix this using a singleton. Create a function that returns a reference to the map, and everywhere you access the map, use that function instead. Instead of mapname.whatever, set it up so you can do mapname().whatever. Define the function to contain a static instance of the map and return it, like so:
std::map<int,int>& mapnam() {   static std::map<int,int> map;   return map;}

Initialization problem solved; and there you have the only thing the singleton pattern does better than a plain old global.

Create an account

Register a new account

• Forum Statistics

• Total Topics
627738
• Total Posts
2978881

• 10
• 10
• 21
• 14
• 13