How can an implementation guarantee that copy constructor of an iterator is no throw?

StackOverflow https://stackoverflow.com/questions/13428851

  •  29-11-2021
  •  | 
  •  

Domanda

Clause 23.2.1.10 of C++11 standard says that

"no copy ctor of a returned iterator throws an exception"

Does this basically state that is it possible for a copy ctor of an iterator not to throw even a bad_alloc presumably (leaving the case where iterator could be just a pointer and here no issues) because it will use the information already constructed in the "returned iterator"? because it is passed by value will the stack be allocated in the called function hence can guarantee no memory issues ?

È stato utile?

Soluzione

That paragraph talks about the iterators used by the containers in the standard library. These iterators are known to be implementable in ways so that they don't throw exception while being copied. For example, none of them have to use any dynamically allocated memory.

The guarantee is just for these iterators, not for iterators in general (even though it is a good idea to follow the example).

Altri suggerimenti

Legal answer: no. Thtat's just your interpretation. It is technically correct, but it may be not the one and only technically correct interpretation.

Technical answer: The point, here, is avoid that an exception thrown by a mutating iterator (think to an inserter or to an output iterator) causes an algorithm to be abandoned while letting a container in an undefined and inconsistent state (think, for example, to a linked list with the links not yet completely re-linked)

It's not just a matter of bad_alloc for iterators that have a dynamically allocated state, but also of an iterator that -during it's own copy- tries to modify a referred item failing in that (for example, because the item assignment throws).

When such a case happens, the iterator is not required to "complete the algorithm" (that would be impossible) but to left the container in a consistent and still manageable state.

I think there is a misinterpretation about the scope of what copy constructor means.

A copy constructor is not responsible for allocating the memory where the object itself will be built, this is provided externally, by the caller.

The requirement, therefore, is that the body of the copy constructor (be it written or generated) does not throw. It is known in C++ that built-in types (int, T*, ...) can be copied without throwing, and from there one can built types that are thus copyable without throwing exceptions (as long as one avoids dynamic resource allocation and/or IO it's automatic).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top