tags:

views:

100

answers:

3
+1  Q: 

stl and exceptions

Hi,

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.

+3  A: 

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.

Gregory Pakosz
A `vector` can't really implement the strong exception guarantee. It can't roll back to the previous state because copying elements might throw, and a vector stores them by value. `vector` only provides the basic guarantee (the vector will be left in a valid state, and no resources will be leaked)
jalf
thank you for the comment jalf
Gregory Pakosz
@jalf: Are you sure? I don't recall that latitude. If you add a 6th element to a vector, and it needs to reallocate, then yes the 4th copy ctor may fail. But at that point, the original array of 5 elements still exists. Rollback probably isn't even needed: you would only swap pointers after all copies succeeded.
MSalters
A: 

I can only answer to the first of the two questions.

The method reserve(K) allocates enough space on the vector to accomodate K elements without doing a costly reallocation, but the vector can grow in size if enough insertions are made.

Luca Martini
+2  A: 

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.

jalf
Yes, found it, thanks.