《More Effective C++》技术篇——限制某个cla
2021-10-24 本文已影响0人
拉普拉斯妖kk
- 如下例,只要继承Counted template就可以限制class所能产生的对象数量,超过了设置的maxObjects就会抛出异常。
#include <stdlib.h>
#include <iostream>
template<class BeingCounted>
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<class BeingCounted>
Counted<BeingCounted>::Counted()
{ init(); }
template<class BeingCounted>
Counted<BeingCounted>::Counted(const Counted<BeingCounted>& rhs)
{ init(); }
template<class BeingCounted>
void Counted<BeingCounted>::init()
{
if (numObjects >= maxObjects)
{
throw TooManyObjects();
}
++numObjects;
}
template<class BeingCounted>
int Counted<BeingCounted>::numObjects = 0;
class Printer: private Counted<Printer> {
public:
// pseudo-constructors
static Printer* makePrinter() { return new Printer(); }
static Printer* makePrinter(const Printer& rhs) { return new Printer(rhs); }
~Printer() {}
using Counted<Printer>::objectCount;
using Counted<Printer>::TooManyObjects;
private:
Printer() {}
Printer(const Printer& rhs) {}
};
template<class Printer>
const size_t Counted<Printer>::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的异常。
}