I’ve been reading a lot of debates about whether the Singleton pattern is good/bad/ugly, and what should be used instead of it.
The common implementation requires an Instance() method that invokes a private constructor if the object has not yet been created.
My question doesn’t really fit the Singleton pattern, but would it be possible to limit the number of instances of a class by overriding new? And if say we only want one instance, return the already created instance?
If this is possible is it even a good idea?
The aim would be that in any class needing access to a class, one would simply declare a private member, which would be initialized the first time, and then referenced for the rest.
ClassA {
MyClass classRef;
}
ClassB {
MyClass classRef;
}
So if MyClassis limited to one instance, depending on the order of instancing, one of these objects will actually create a new MyClass, and the other will just obtain it’s reference.
Objects can be allocated statically, on the stack, and within other objects. If you want just one instance, you need to disallow all of these somehow. Overloading
operator newwon’t help you with this. Making the constructorsprivateorprotectedwill, but this will disableoperator newfor the users of the class as well.Moreover, what
operator newreturns is not an object, but a block memory in which the object will be created. If you return an already allocated block, a constructor will be run over it each timeoperator newis called.