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
- Use a
try catchclause at all occurrences of a possible vector memory allocation to catch the exception. - Overload
newand 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?