《More Effective C++》技术篇——限制某个class所能产生的对象数量

  • 【《More Effective C++》技术篇——限制某个class所能产生的对象数量】如下例,只要继承Counted template就可以限制class所能产生的对象数量,超过了设置的maxObjects就会抛出异常。
    #include #include template class Counted { public: class TooManyObjects{}; //这是可能被抛出的exceptions。 static int objectCount() { return numObjects; }protected: Counted(); Counted(const Counted& rhs); ~Counted() { --numObjects; }private: static int numObjects; static const size_t maxObjects; void init(); //用以避免ctor码重复出现。 }; template Counted::Counted() { init(); }template Counted::Counted(const Counted& rhs) { init(); }template void Counted::init() { if (numObjects >= maxObjects) { throw TooManyObjects(); }++numObjects; }template int Counted::numObjects = 0; class Printer: private Counted { public: // pseudo-constructors static Printer* makePrinter() { return new Printer(); } static Printer* makePrinter(const Printer& rhs) { return new Printer(rhs); } ~Printer() {}using Counted::objectCount; using Counted::TooManyObjects; private: Printer() {} Printer(const Printer& rhs) {} }; template const size_t Counted::maxObjects = 5; int main() { auto p1 = Printer::makePrinter(); auto p2 = Printer::makePrinter(); auto p3 = Printer::makePrinter(); std::cout << "now Printer num = " << p1->objectCount() << std::endl; auto p4 = Printer::makePrinter(*p1); auto p5 = Printer::makePrinter(*p2); std::cout << "now Printer num = " << p1->objectCount() << std::endl; //auto p6 = Printer::makePrinter(*p3); //抛出TooManyObjects的异常。 }

    推荐阅读