Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::vector::push_back permitted to throw for any reason other than failed reallocation or construction?

Consider:

std::vector<int> v;
v.reserve(1);
v.push_back(1); // is this statement guaranteed not to throw?

I've chosen int because it has no constructors that could throw - obviously if some copy constructor of T throws, then that exception escapes vector<T>::push_back.

This question applies as much to insert as push_back, but it was inspired by Is it safe to push_back 'dynamically allocated object' to vector?, which happens to ask about push_back.

In the C++03 and C++0x standard/FCD, the descriptions of vector::insert say that if no reallocation happens, iterators/references before the insertion point remain valid. They don't say that if no reallocation happens, no exception is thrown (unless from constructors etc of T).

Is there anything elsewhere in the standard to guarantee this?

I don't expect push_back to do anything that could throw in this case. The GNU implementation doesn't. The question is whether the standard forbids it.

As a follow-up, can anyone think of a reason why any implementation would throw? The best I can think of, is that if a call to reserve ends up increasing the capacity to a value in excess of max_size(), then insert perhaps is permitted to throw length_error when the max size would be exceeded. It would be useless to increase capacity beyond max_size(), but I don't immediately see anything forbidding that, either [Edit: your allocator would probably stop you increasing capacity beyond max_size, so this suggestion might be no good.]

like image 787
Steve Jessop Avatar asked Nov 15 '10 16:11

Steve Jessop


1 Answers

Well, it kind of depends on the allocator you are using.

Apart from the allocator, the only thing you can rely on is that push_back() and push_front() are guaranteed to be noop if an exception is thrown (23.1-10). The standard definitely doesn't forbid the push_back() from throwing exceptions.

like image 142
Šimon Tóth Avatar answered Nov 14 '22 03:11

Šimon Tóth