0
101 Apr 22, 2010 at 08:12

Hello, sorry for bothering.

While browsing the net in search for a safe, easily deallocable singleton I’ve come upon the solution I’m posting below. One nice thing about it is that the singleton instance is not allocated on the heap but instead declared as a static variable inside of the instance method, which guarantees both the automatic initialization when the method is first called and easy cleanup once the program terminates. Also, the copy constructor and the “=” operator are both declared as private and overloaded so as to prevent the instance to be copied, but that should be obvious. Decided to share.

I hope it’s not a repost.

class cSingleton {
public:
static cSingleton* instance() {
static cSingleton ptr;
return &ptr;
}

private:
~cSingleton() { }
cSingleton() { }
cSingleton(const cObjectManager& inst) {}
void operator=(const cSingleton&) const {}
};


#### 7 Replies

0
101 Apr 22, 2010 at 08:45

Looks like a good implementation.

Still, I hope you are familiar with the problems of singletons (order of destruction), and the alternatives.

In my own development I have found that a monostate (static methods/variables only) class is almost always a better solution than a singleton.

0
101 Apr 22, 2010 at 11:20

This is indeed the standard C++ way for singletons, but note that the solution is not thread-safe.

0
101 Apr 22, 2010 at 13:53

I have never found any practical use for singletons. Probably the closest altertative I use is activation of a class instance globally and accessing the instance through a global accessor. Upon destruction of an instance check if it’s active and deactivate if so.

0
101 Apr 23, 2010 at 08:04

@JarkkoL

I have never found any practical use for singletons. Probably the closest altertative I use is activation of a class instance globally and accessing the instance through a global accessor. Upon destruction of an instance check if it’s active and deactivate if so.

Factory Design Patterns are useful. They are often a singleton as you normally only want one factory, with global availability, through a single access point.

0
101 Apr 23, 2010 at 11:13

I use factory pattern as well, but I haven’t had any use of making it a singleton. Globally accessible yes, but not a singleton.

0
101 Apr 23, 2010 at 12:49

@geon: I didn’t know about monostates until your post; looked them over and they indeed look like a safe alternative to singletons.

My own predilection towards the singleton pattern stemmed from the fact that Ogre makes extensive use of it.

0
101 Apr 23, 2010 at 12:56

Well, what I have heard, OGRE isn’t exactly a prime example of good software engineering practices and is often referred as being over-engineered with excessive inheritance hierarchies, etc.