Reputation: 5714
In the code
std::vector<int> vec(length);
vec.resize(2*length);
vec.push_back(4);
vec.reserve(3*length);
all statements might throw a bad_alloc
exception, if the allocation a n-times length
integers fails (see reserve and resize).
I see two approaches to handle this exception
try catch
clause at all occurrences of a possible vector memory allocation to catch the exception.new
and add exception handling there for all occurrences.I maintain a large code base, thus the first option seams rather cumbersome and will also spoil the readability of the code.
What is the best best practise to check if a memory allocation of a std::vector
worked?
Upvotes: 1
Views: 1164
Reputation: 403
Catch std::bad_alloc at the program or module level, at a point where you can properly handle it by terminating the program or canceling what the module did.
At the program level: Add a try catch in your main, display a message then exit.
At the module level: Add a try catch around the entry point DoStuffWhichRequiresALotOfMemory() of your module. Make sure that after std::bad_alloc is thrown your program is still in a valid state, f.i. the module has a separate state to the rest of the program or it's functional without side effects. Display a message and you are done.
Handling memory allocation failure at such a low level is impractical. If you need these guarantees, allocate all the memory beforehand (for the whole module, not only for your vector) and use an allocator. Then you only have one point where it can fail.
I know this does not directly answer the question, but I urge you to think about your problem again.
Upvotes: 2