throwing exception in operator new function

I must create a class with its own operator new. This operator should allocate ten objects, and on the eleventh object “run out of memory” and throw an exception.I don't know how to allocate storage in my function operator new for ten object and then to throw an exception.If I put throw statement after returning ::operator new it won't execute.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include<iostream>
using namespace std;
class A
{
      public:
             class OutOfRange{};
             A(){cout<<"constructor\n";}
      void* operator new [](size_t sz)
            {
              return::operator new(sz);
              throw OutOfRange();
            }
            void operator delete[](void* p)
            {
                 cout<<"delete\n";
                 return::operator delete(p);
                 }
            ~A(){cout<<"destructor\n";}
};
int main()
{
    A* pi=0;
  try{
  pi=new A[10];
}
catch(A::OutOfRange){
  delete pi; 
}
 getchar();  
}
This operator should allocate ten objects, and on the eleventh object “run out of memory” and throw an exception.

That sounds like "keep track of how many objects have been allocated", i.e. throw a fit if the current allocation request would exceed the limit.
I don't know how to allocate storage in my function operator new for ten object and then to throw an exception.
As described above by keskiverto.

If I put throw statement after returning ::operator new it won't execute.
It's your operator new that is to do the throw.
With keeping track of objects and trowing exception in constructor everything is OK.But I don't know how to throw exception in my overloaded version of operator new .Is it possible?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A {
  static const size_t Alimit = 10;
  static size_t Acount;
  //
};

A::Acount = 0;

void* A::operator new () {
  if ( Acount < Alimit ) {
    // allocate
    ++Acount;
  } else {
    throw
  }
}

Extrapolate to array version and delete().
Topic archived. No new replies allowed.