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.]
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.
来源:https://stackoverflow.com/questions/4186431/is-stdvectorpush-back-permitted-to-throw-for-any-reason-other-than-failed-re