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

痞子三分冷 提交于 2019-12-10 02:14:20

问题


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.]


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!