Hello
I want to put a limit on the number of instances you can make of a class.
I have the following code:
class A{
static int cnt;
int x;
public:
A()
{
cout<<"ctor called\n";
}
void* operator new(size_t size_in)
{
if(cnt<=10)
{
void *p=malloc(size_in);
if(p==NULL)
throw bad_alloc();
else
{
cout<<"Memory allocation successful\n";
++cnt;
return p;
}
}
else
throw bad_alloc();
}
~A()
{
cout<<"Cleaning up the mess\n";
}
};
int A::cnt=0;
int main()
{
A *a[20];
for(int i=0;i<20;++i)
{
try{
a[i]=new A();
}catch (bad_alloc &e)
{
cout<<"Error in allocating memory\n";
}
}
try{
A b;
}catch (bad_alloc &e)
{
cout<<"Error in allocating memory on stack\n";
}
return 0;
}
Using a static counter and overloading the new operator I am able to put a limit on the number of objects that can be created on heap.
Now,I want to limit the number of instances created on Stack also. One way is to make constructor private and provide a public API which first checks the counter and then returns accordingly. Is there any other way of doing this??
Aucun commentaire:
Enregistrer un commentaire