条款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下测试过,没有问题。我在原有基础上,在析构中,加入了对对象数量的递减。这样做为了将来对象引用计数打下基础。