May STL iterator methods throw an exception

Destructors cannot throw exceptions (so stack expansion can end during exception handling) and must release any resources allocated to the object (therefore, there is no leakage of resources). The construction of an object that contains several other objects (or several resources are allocated) can write pointers to them in the STL container. Therefore, the destructor would use the following methods associated with the iterator:

  • begin() , end() for the container
  • operator++ for a valid iterator
  • operator* or operator-> for a valid iterator

But to ensure that the destructor does not throw exceptions and free resources, you will need to rely on methods that never throw exceptions.

Can you rely on these methods without ever throwing exceptions? It is hard to imagine a practical implementation that will throw exceptions, since under the hood the STL iterator is essentially a pointer. But does standard C ++ have a request that these methods never throw an exception? I did not find a clear statement in the C ++ standard.




Change An interesting case for C ++ 03 if you want to have a container of pointers to resources . There are good reasons for this; for example, if you have polymorphic resources. Since BjΓΆrn Pollex indicates in its answer that if you use a resource container (e.g. std::list< Resource > ) and not a container of resource pointers, the container destructor will take care of destroying (releasing) the Resource objects for you.

+18
c ++ exception stl
Oct 26 '11 at 12:18
source share
4 answers

operator ++ for a valid iterator

The C ++ standard (I mean the N3290 project) does not guarantee nothrow for the iterator increment operator.

For example, std::istreambuf_iterator::operator++ affects the call to std::basic_streambuf::sbumpc . sbumpc can call uflow , which in turn can throw an exception.

+15
Oct 26 '11 at 13:08
source share
β€” -

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

This is from the C ++ 03 standard. I don't think the standard goes further.

Btw. it 23.1.10

+6
Oct 26 '11 at 12:25
source share

Thus, the destructor will use the following iterator-related Methods

No, it will not. The destructor of this object will simply call the container destructor, which, in turn, is guaranteed to not throw an exception.

If you use RAII correctly, you will almost never run into a scenario where you must explicitly allocate resources. This can be achieved using the shared_ptr or unique_ptr storage container or using something like Boost.Pointer Container .

+1
Oct 26 '11 at 12:22
source share

According to http://www.tenouk.com/Module31.html, these operations (for '*' and '->' this also depends on the stored type) are not thrown away for STL containers.

0
Dec 23
source share



All Articles