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?
std::alignbut 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.shared_ptron something that the system can deallocate itself (when the stack frame goes away) is just asking for trouble. Even if this is done inmain, 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.)