Raedwald
Raedwald

Reputation: 48644

May STL iterator methods throw an exception

Destructors may not throw exceptions (so stack unwinding can complete during exception handling), and must deallocate any resources allocated to the object (so no resources leak). A design for an object that contains several other objects (or is allocated several resources) might record pointers to them in an STL container. The destructor would therefore use the following iterator-related methods:

But to guarantee that the destructor both does not throw exceptions and deallocates its resources you would need to rely on those methods never throwing exceptions.

Is it safe to rely on those methods never throwing exceptions? It is hard to imagine a practical implementation that would throw exceptions, as under the hood an STL iterator is essentially a pointer. But does standard C++ require that those methods never throw exceptions? I've not found a clear statement in the C++ standard.


Edit: The interesting case is for C++ 03 when you want to have a container of pointers to resources. There are good reasons for doing this; for example, if you have polymorphic resources. As Björn Pollex points out in his answer, if you use a container of resources (such as a std::list< Resource >) rather than a container of pointers to resources, the destructor of the container will take care of destruction (deallocation) of the Resource objects for you.

Upvotes: 19

Views: 6483

Answers (4)

kitek
kitek

Reputation: 117

According to http://www.tenouk.com/Module31.html these operations (for '*' and '->' it depends also on the type stored) are no throw for STL containers.

Upvotes: 0

mloskot
mloskot

Reputation: 38892

operator++ for a valid iterator

The C++ standard (I refer to N3290 draft) does not give nothrow guarantee for increment operator of iterators.

For example, std::istreambuf_iterator::operator++ effects in call to std::basic_streambuf::sbumpc. The sbumpc may call uflow which in turn may throw exception.

Upvotes: 18

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36433

no copy constructor or assignment operator of a returned iterator throws an exception

That's from the C++03 standard. I don't think that the standard goes any further than that.

Btw. it's 23.1.10

Upvotes: 6

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

The destructor would therefore use the following iterator-related methods

No it would not. The destructor of that object would just call the destructor of the container, which would in turn be guaranteed to not throw an exception.

If you use RAII correctly, you will almost never run into a scenario where you have to explicitly release resources. This could be achieved by have the container store shared_ptr or unique_ptr, or by using something like Boost.Pointer Container.

Upvotes: 1

Related Questions