Please help to comment whether my following understanding is correct,
1. whether or not we are using auto_ptr to allocate new object on heap (using new), there may be bad_alloc exceptions;
2. when we met with such exceptions, we catch it (bad_alloc) and try to mininize the operation in catch handler block (since when bad_alloc occurs, it means memory is running out, we can not do anything complex in handler).
Both are correct? Please feel free to correct me if I am wrong.
thanks in advance,
1. auto_ptr is used to ensure that the memory is freed. It has nothing at all to do with allocation. So yes, whether or not you use it, the new operator may throw. Unless you use the non-throwing variant.
2. Catching bad_alloc is something that is typically only done in two places:
1) At the top level of your program, to ensure graceful termination in OOM situations (there's not much you can do about them other than terminating).
2) Around areas that allocate an unusually large amount of memory. In such cases, you can just abort the memory-intensive operation and keep your program alive.
If we met with bad_alloc, do we need to use delete or delete to free the memory in exception handler block?
Originally Posted by CornedBee
No. bad_alloc means there wasn't enough memory to allocate what you asked for. So since it didn't allocate anything, you don't need to delete anything.
Originally Posted by George2
Thanks for your clarification, cpjust!
My question is answered.
Originally Posted by cpjust