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

  • 如下例,只要继承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的异常。
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值