开发者

stl and exceptions

开发者 https://www.devze.com 2023-01-15 12:17 出处:网络
If I use reserve(开发者_C百科) to reserve enough elements for a vector, will push_back() (or insert()) throw any exceptions?

If I use reserve(开发者_C百科) 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消