Given a class, I would like to limit the number of objects created from this class to a given number, say 4.
Is there a method to achieve this?
Given a class, I would like to limit the number of objects created from this class to a given number, say 4.
Is there a method to achieve this?
基本思想是计算某个静态变量中创建的实例的数量。我会这样实现它。存在更简单的方法,但这种方法有一些优点。
template<class T, int maxInstances>
class Counter {
protected:
Counter() {
if( ++noInstances() > maxInstances ) {
throw logic_error( "Cannot create another instance" );
}
}
int& noInstances() {
static int noInstances = 0;
return noInstances;
}
/* this can be uncommented to restrict the number of instances at given moment rather than creations
~Counter() {
--noInstances();
}
*/
};
class YourClass : Counter<YourClass, 4> {
}
您正在寻找实例管理器模式。基本上,您所做的就是将该类的实例化限制为管理器类。
class A
{
private: //redundant
friend class AManager;
A();
};
class AManager
{
static int noInstances; //initialize to 0
public:
A* createA()
{
if ( noInstances < 4 )
{
++noInstances;
return new A;
}
return NULL; //or throw exception
}
};
一种更短的方法是从构造函数中抛出异常,但这很难做到:
class A
{
public:
A()
{
static int count = 0;
++count;
if ( count >= 4 )
{
throw TooManyInstances();
}
}
};