Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are standard iterator operations allowed to throw?

Tags:

c++

Consider a standard iterator where it is necessary to allocate memory for traversing a data structure. Does the standard allow an iterator to throw an exception if memory cannot be allocated? As an example, think of an input iterator for tree data structures. In this case, to traverse the tree you have to either add and maintain a pointer to the parent of each node (which would slow down operations not needing such a pointer, as for insert/erase/find on the tree) or use a stack to help the iterator store the pointers to the traversed nodes. In this case, while advancing the stack could grow until there is no more free memory and the iterator is compelled to throw.

like image 384
Martin Avatar asked Feb 19 '12 00:02

Martin


1 Answers

Yes an iterator method in C++ is allowed to throw and as you pointed out can throw in certain circumstances.

The only class of functions in C++ that can't throw is a destructor. And really that's just by convention (because it makes certain operations nearly impossible to do correctly). Destructors can throw, it's just very bad to let them do so.

Individual functions can be marked with throw() to prevent them from throwing.

like image 131
JaredPar Avatar answered Sep 21 '22 06:09

JaredPar