Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl and exceptions

Tags:

c++

stl

If I use reserve() to reserve enough elements for a vector, will push_back() (or insert()) throw any exceptions?

Is there a reference somewhere that specifies which stl function throw / not throw any exceptions?

Thank you.

like image 551
twf Avatar asked Sep 03 '26 18:09

twf


2 Answers

If I use reserve() to reserve enough elements for a vector, will push_back() (or insert()) throw any exceptions?

It won't need to perform a reallocation, and so the vector itself won't throw any exceptions. The elements you're inserting might throw exceptions when being copied into the vector, though, so push_back and insert can still throw exceptions.

Is there a reference somewhere that specifies which stl function throw / not throw any exceptions?

Yes, the C++ standard contains that information.

like image 171
jalf Avatar answered Sep 05 '26 10:09

jalf


I would say push_back throws when copy construction throws.

Now an exception safe implementation of std::vector will maintain the vector's state as it was before you called push_back or insert so that you can keep using the object.

Also, have a lookt at Lessons Learned from Specifying Exception-Safety for the C++ Standard Library by David Abrahams.

like image 32
Gregory Pakosz Avatar answered Sep 05 '26 10:09

Gregory Pakosz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!