Search code examples
c++exceptionvectorstandardsc++20

What if std::vector::insert(pos, value) with an invalid pos?


According to cppref:

constexpr iterator insert( const_iterator pos, const T& value );

Return value

Iterator pointing to the inserted value.

Complexity

Constant plus linear in the distance between pos and end of the container.

Exceptions

If an exception is thrown when inserting a single element at the end, and T is CopyInsertable or std::is_nothrow_move_constructible::value is true, there are no effects (strong exception guarantee).

If pos is invalid, the documentation doesn't clearly describe the following issues:

  1. What's the return value?
  2. Whether an exception will be thrown?

So, my question is:

What if std::vector::insert(pos, value) with an invalid pos?


Solution

  • std::vector is a sequence container. Table 77: Sequence container requirements listes the first argument of every insert overload as being p which is defined just before the table as : "p denotes a valid constant iterator to a" where a is the vector.

    So the position iterator is required to be a valid iterator to a. Unless a different consequence is described, failing to respect a requirement of a feature is by default Undefined Behavior.