More Effective C++ 26: Limiting the number of objects of a class
1. Make the constructors private to control the constructing of objects.
2. Declare public peudo-constructors whichby clients get the objects.
3. Better declare the object static in function, not in class.
. static objects in functions are initialized the first time the function is called while those in classes are always initialized
. the order of initialization of static objects in different classes are not defined
. however, functions containing static objects cannot be declared inline
namespace PrintingStuff {
class Printer {
public:
void submitJob(const PrintJob& job);
void reset();
void performSelfTest();
...
friend Printer& thePrinter();
private:
Printer(); //[i] private ctors[/i]
Printer(const Printer& rhs); // don't define this function so as
// to prevent copying
...
};
Printer& thePrinter() // [i]peudo-constructor[/i]
{
static Printer p; // [i]static var in function[/i]
return p;
}
}