【问题标题】:What if std::vector::insert(pos, value) with an invalid pos?如果 std::vector::insert(pos, value) 的 pos 无效怎么办?
【发布时间】:2021-09-11 19:40:02
【问题描述】:

根据cppref

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

返回值

指向插入值的迭代器。

复杂性

pos 和容器末端之间的距离为常数加线性。

例外情况

如果在末尾插入单个元素时抛出异常,并且 T 是 CopyInsertable 或 std::is_nothrow_move_constructible::value 为真,没有 效果(强异常保证)。

如果pos 无效,说明文档没有明确描述以下问题:

  1. 返回值是多少?
  2. 是否会抛出异常?

所以,我的问题是:

如果 std::vector::insert(pos, value) 无效 pos怎么办?

【问题讨论】:

  • 使用vector你甚至不能检查没有UB的pos是否有效,因为它通常是一个原始指针,如果指针不属于同一个对象或数组,则更少/更大的指针比较是UB。
  • @dewaffled:这在 C 中是未定义的行为,但在 C++ 中绝不是未指定的bool

标签: c++ exception vector standards c++20


【解决方案1】:

std::vector 是一个序列容器。 Table 77: Sequence container requirements 列出每个insert 重载的第一个参数为p,它被定义为just before the table"p 表示a"的有效常量迭代器" 其中@987654328 @ 是向量。

所以位置迭代器必须是a 的有效迭代器。除非描述了不同的后果,否则默认情况下不遵守功能要求是未定义行为。

【讨论】:

    【解决方案2】:

    Iteator requirements, 15

    (15) 无效的迭代器是可能是单数的迭代器 (223)

    (223) 这个定义适用于指针,因为指针是迭代器。这 取消引用已失效的迭代器的效果是 未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 2013-09-27
      • 2012-06-07
      • 1970-01-01
      • 2014-12-14
      • 2014-12-13
      • 2015-11-23
      相关资源
      最近更新 更多