nit*_*ian 2 c++ object instantiation
给定一个类,我想将从这个类创建的对象数量限制为给定的数字,比如4.
有没有办法实现这个目标?
基本思想是计算某些静态变量中创建的实例的数量.我会像这样实现它.存在更简单的方法,但这个方法有一些优点.
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> {
}
Run Code Online (Sandbox Code Playgroud)