Problem:
How can I limit the number of class objects? Like 1, 10 and so on.
Method (1):
If you define a class's constructor as private, you cannot instantiate the class. But how do you create 1 objects out of it? There are 2 types of methods:
1. Declare a friend function, then the constructor can be called in the friend function, and the static limit is used to create the object, then only one object is guaranteed. A similar definition is as follows:
1 classPrinter2 {3 Public:4Friend printer&theprinter ();5 Private:6 Printer ();7Printer (Constprinter&RHS);8 };9printer&theprinter ()Ten { One StaticPrinter p; A returnp; -}
2. The same effect can be achieved by defining a static member function instead of the friend function above, that is, the call is troublesome and requires the class name to call the function, but this is also possible, but it can be resolved by defining the class in a namespace (namespace). The namespace can then be invoked directly using the function name (see how to define namespaces). Namespaces can also be used to prevent name collisions, and the benefit of declaring an object in a function is that the object is created only when the function is called. Note: Try not to create static objects in inline functions, possibly producing multiple replicas.
1 classPrinter2 {3 Public:4 Staticprinter& Theprinter ();//Watch this .5 Private:6 Printer ();7Printer (Constprinter&RHS);8 };9printer&theprinter ()Ten { One StaticPrinter p; A returnp; -}
Method (2): Define a counter in the class that limits the number of instance objects by counter, and throws an exception once the number of limits is created. (Consider inheritance, and the derived class object is also counted by T.)
"More effective C + +" clause 26 limiting the number of class objects