C++ – Should I throw std::bad_alloc

cexceptions

I am allocating memory on the stack, and distributing it manually to shared pointers. I end up doing something like this at startup (I've simplified it by ignoring alignment issues):

char pool[100];

std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj;
pool += sizeof(pool);

Of course, it is possible that the 100 is not enough, so in that case I'd like to throw an exception:

char pool[100];
char* poolLimit = pool + 100;

if (pool + sizeof(Obj) >= poolLimit)
  throw std::bad_alloc(); // is this a good idea?

std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj;
pool += sizeof(pool);

Is it correct to throw a std::bad_alloc here? Or should I just throw std::runtime_error?

Best Answer

(I'm assuming you are writing an user-mode application here, not a kernel module, device driver or network stack).

Throw std::bad_alloc. Only an idiot would try to catch that.

But it doesn't really matter what you throw because the application is dead at that point anyway. What you want is for the application to quit at that point in a clear and unambiguous way. Calling abort would be even better.

If you are operating out of a fixed buffer you really need to make sure it is big enough for all needs.