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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With