Original Post
There are many threads here that ask about singletons and why not to use them, since there seem to be many cases where you should only have one instance of a class and it should have global access. Usually the answer is that a class almost never needs global access and if you only want one instance, don't create more than one. I'm completely sold on the first argument but it seems to me that it would be nice to enforce the second one. For example, the class might be a part of a library and it's users might create more than one instance of it (because they won't be convinced that they shouldn't). So I thought that something like a "Local Singleton" design pattern might be useful (and not as dangerous as the "regular" singleton). So I decided to write a small class that does this: Here's an example of it: Of course, a compile-time error would have been better (instead of the assert() which will trigger at run-time), but this is just a simple example. So what do you think about this? Does it work properly? Is it stupid? Useless? The invention of the century? [grin]
#include <cassert>
template <class T>
class LocalSingleton {
private:
LocalSingleton(const LocalSingleton &);
LocalSingleton & operator=(const LocalSingleton &);
static int s_count;
public:
LocalSingleton() {
if (++s_count > 1)
assert(!"Can't create more than one instance");
}
~LocalSingleton() {
--s_count;
assert(s_count == 0); // Just in case...
}
};
template <class T>
int LocalSingleton<T>::s_count = 0;
#include "LocalSingleton.h"
class Renderer : public LocalSingleton<Renderer> {};
class TextureManager : public LocalSingleton<TextureManager> {};
int main()
{
Renderer r; // OK
// Renderer r2; // Triggers an assertion
TextureManager tm; // OK
// TextureManager tm2; // Triggers an assertion
}