将类的对象实例化数量限制为给定数量 [英] Restrict the number of object instantiations from a class to a given number
本文介绍了将类的对象实例化数量限制为给定数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个类,我想将从该类创建的对象的数量限制为给定的数量,例如4.
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?
推荐答案
基本思想是计算某个静态变量中已创建实例的数量.我会这样实现.虽然存在更简单的方法,但是这种方法有一些优点.
The basic idea is to count the number of created instances in some static variable. I would implement it like this. Simpler approaches exist, but this one has some advantages.
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> {
}
这篇关于将类的对象实例化数量限制为给定数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文