I need class, which cann't have more than N instances. How can i make it?
First of all, why?
Once we get that question out of the way, you already know how to make a class that allows for just one instance, I assume? Usually, you do that with a static instance and a private constructor (or some variation thereof). To generalise that to N instances, all you need to do is store a static array of instances.
Finally, seriously, WHY?
Use a static variable that is called count for example. In the constructor just add one each time an object is created:
struct myclass
{
myclass()
{
if(count == N) /*throw some exception!*/
++count;
}
~myclass()
{
--count;
}
private:
static std::size_t count = 0;
};
Use a factory method for instance creation. Also have a static variable in the class to to keep track of number of instances in existence. If the upper limit is hit you can trow an exception or return an already created object, depends on your design. To enable object creation only through the factory method you'll have to make the ctor private.
Unless it 100% makes sense for that class to limit itself to N instances, you should really wrap the class into a static access class that will hardly limiting the numbers of instances.
The only purpose I can see for something like this is to create a pool of "workers" (or something similar). The best way to achieve this is to create two classes: one "WorkerPool" class and one "Worker" class. Something like this:
typedef boost::shared_ptr<Worker> WorkerPtr;
class Worker{
// do the worker stuff here
}
class WorkerPool{
public:
const int MAX_WORKERS = 20;
WorkerPool(){ for(int i=0;i<MAX_WORKERS;i++)
_pool.push_back(WorkerPtr(new Worker()) );
}
WorkerPtr get(){
if(_pool.size()>0) return _pool.pop_front();
return WorkerPtr();
}
void release(WorkerPtr w){
return _pool.push_back(w);
}
private:
std::list<WorkerPtr> _pool;
}
It's just an example, you may do it differently (including making the WorkerPool a singleton, synchronizing get() instead of returning NULL, etc.) - but you get the picture.
First, a compiling and working version of the code "public" is:
static Singleton* Instance() {
static Singleton *p;
if(!p) { p = new Singleton; }
return p;
}
For the sake of the exercise, you could modify to N instances by using
static Singleton* Instance(int n) {
static Singleton *p[N];
if(!p[n]) { p[n] = new Singleton; }
return p[n];
}
Error checking omitted.