More Effective C++之26

条款26:限制某个class所能产生的对象数量
允许零个或者一个对象
       零个,很简单,将对象的构造函数私有化。一个,也很简单,Singleton模式。我前面也有Blog对局部静态对象进行了探讨。
 
不同对象的构造状态
       对象的存在有三种状态,(1)对象自己(2)存在于派生类对象中(3)作为成员对象存在于某个更大的对象中。我们通常做这样的限制的时候,通常这样做
class A
{
private:
       A(){}

       A(const A&){}

public:

       static A* MakeA(){return new A();}

       static A* MakeA(const A& a){return new A(a);}

};
为了避免资源泄漏,通常可以把这样的对象放在智能指针中。
 
允许对象生生灭灭
       当多于一个对象的时候,可以在MakeA()中作一个限制,如果超过某一个数量返回NULL或者抛出异常。
class A
{
private:
       A(){}

       A(const A&){}

       ~A(){--numObjects ;}

       static size_t numObjects;

static const size_t maxObjects;

public:

       static A* MakeA()

{
       if(numObjects >= maxObjects)
              return NULL;
       else
{
       ++numObjects;
return new A();
}
}

       static A* MakeA(const A& a)

{
if(numObjects >= maxObjects)
              return NULL;
       else
{
       ++numObjects;
return new A(a);
}
}
};
size_t A::numObjects = 0;
const size_t A::maxObjects = 10;
 

一个用来计算对象个数的Base Class

       考虑如下代码:
template < class BeingCounted >
class CCounted  
{
public :
       class TooManyOjects {};
       static int ObjectCount (){ return numberObjects ;}
 
protected :
       CCounted (){ init ();}
       CCounted ( const CCounted & rhs ){ init ();}
       virtual ~ CCounted (){-- numberObjects ;}
 
private :
       static const int maxObjects ;
       static int numberObjects ;
       void init ()
       {
              if ( numberObjects >= maxObjects )
                     throw TooManyOjects ();
              ++ numberObjects ;
       }
};
 
template < class BeingCounted >
int CCounted < BeingCounted >:: numberObjects = 0;
 
template < class BeingCounted >
const int CCounted < BeingCounted >:: maxObjects = 10;
 
class Printer : private CCounted < Printer >
{
public :
       static Printer * makePrinter (){ return new Printer ;}
       static Printer * makePrinter ( const Printer & rhs ){ return new Printer ( rhs );}
       virtual ~ Printer (){}
       using CCounted < Printer >:: ObjectCount ;
private :
       Printer (){}
       Printer ( const Printer &){}
};
以下代码,我在VC6下测试过,没有问题。我在原有基础上,在析构中,加入了对对象数量的递减。这样做为了将来对象引用计数打下基础。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值