Can any standard C ++ 98 container operations throw std :: bad_alloc?

I tried to find out if try capture is needed in the following code:

std::vector<int> values;
// ignore that this can throw std::bad_alloc
values.push_back(1);
try {
    for (std::vector<int>::iterator iter = values.begin();
         iter != values.end(); ++iter) {
         ++(*iter);
    }
} catch (const std::bad_alloc&) { 
    // Is this needed?
}

Looking through the C ++ 1998 standard, the only thing I can find is a hint at section 23.1, Container Requirements, which contains a sentence:

A copy of this argument is used for any performed memory allocation by these constructors and all member functions throughout the life cycle of each container object.

My interpretation is that any member function in a container can call a dispenser, so any member function can call std :: bad_alloc. Am I too paranoid or is it really so?

+3
source share
3 answers

, 23.1/10, , , :

  • no erase(), pop_back() pop_front() .
  • .

, begin() end(), , ; , - .

+4

, bad_alloc.

, (std::vector::at()), .

, , push_back() , , . , . , (begin(), end()).

+2

- , , bad_alloc.

I would not worry about that begin, and endejected as far as the container, but there is another problem: the implementation of the iterator. If iterators are of class type, then theoretically the construction (or assignment) of such instances can throw very well. Therefore, although I do not think that the likelihood that any randomly selected standard implementation of the library will throw, you cannot exclude it.

0
source

All Articles