2

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?

  • 5
    Um...you know that doing that with something on the stack is a disastrously bad idea, right? – Steven Burnap Nov 6 '14 at 3:07
  • Why are you doing this? Looks like an x/y problem. – Ben Nov 6 '14 at 9:14
  • 1
    @Ben it's part of an implementation of a heterogenous memory pool. The actual implementation uses std::align but for the purpose of this question that kind of detail wasn't necessary. The fact that it allocates on the stack is a minor detail, it could be on the heap as well. – quant Nov 6 '14 at 10:09
  • There is a third option: static memory. Using shared_ptr on something that the system can deallocate itself (when the stack frame goes away) is just asking for trouble. Even if this is done in main, you're still better off using something other than the stack as stacks are often limited in size. If your goal is to have a large memory pool used for the lifetime of the program, static memory is a far better idea as it never goes away until the program quits and it can usually be of arbitrarily large size (depending on physical RAM/disk.) – Steven Burnap Nov 6 '14 at 19:49
3

(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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.