How can an implementation ensure that the iterator copy constructor is not thrown?

Clause 23.2.1.10 of the C ++ 11 standard states that

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

Does this mean, in principle, that a copy of the ctor iterator may not even cause bad_alloc, presumably (leaving the case where the iterator may just be a pointer and there is no problem), since it will use information already built into the "returned iterator"? because it is passed by value, the stack in the called function will be allocated, therefore, can it guarantee the absence of memory problems?

+4
source share
3 answers

This section talks about iterators used by containers in the standard library. It is known that these iterators are implemented in such a way that they do not throw an exception when copying. For example, none of them should use any dynamically allocated memory.

The guarantee is intended only for these iterators, and not for iterators in general (although it is nice to follow an example).

+1
source

Legal answer: no. This is just your interpretation. This is technically correct, but it may not be the only technically correct interpretation.

Technical answer: here it should be avoided that the exception created by the mutating iterator (think of an insertor or output iterator) forces the algorithm to fail, allowing the container to be undefined and inconsistent (think, for example, of a linked list with links that are not yet fully related )

This is not just a bad_alloc question for iterators who have a dynamically distributed state, but also an iterator who, being its own copy, tries to change the related element in this case (for example, because the item clause is selected).

When this happens, the iterator does not need to โ€œcomplete the algorithmโ€ (this would be impossible), but leave the container in a constant and still manageable state.

+1
source

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

The copy constructor is not responsible for the allocation of memory in which the object itself, which is provided by the external caller, will be built.

Therefore, the requirement is that the body of the copy constructor (whether written or generated) does not throw. In C ++, it is known that built-in types ( int , T* , ...) can be copied without metalization, and from there types can be created that can be copied without exception (if one avoids dynamic resource allocation and / or automatic input).

0
source

Source: https://habr.com/ru/post/1446612/


All Articles