Jump to content
  • Advertisement
Sign in to follow this  
TEUTON

Singleton Problem

This topic is 4533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
It's silly. Read this:
http://www.gamedev.net/reference/articles/article1825.asp

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by TEUTON
But 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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!