【问题标题】:Why is std::string_view::starts_with(const charT*) not noexcept? [duplicate]为什么 std::string_view::starts_with(const charT*) 不是 noexcept? [复制]
【发布时间】:2022-01-26 20:05:14
【问题描述】:

在cppreference 上,std::basic_string_view<CharT,Traits>::starts_with 存在三个重载:

constexpr bool starts_with( basic_string_view sv ) const noexcept; (1)
constexpr bool starts_with( CharT c ) const noexcept; (2)
constexpr bool starts_with( const CharT* s ) const; (3)

为什么第三个没有标记为noexcept?类似于std::basic_string_view<CharT,Traits>::ends_with

【问题讨论】:

  • 第三个可能会因非空终止 C 字符串而失败(UB),允许异常?
  • 有趣,MS 的实现是noexcept : docs.microsoft.com/en-us/cpp/standard-library/…
  • @AdrianMole std::string_view 的构造函数执行动态分配还是执行复制?我希望不会。
  • @MatG 幸运的是,没有。然而,有些构造函数可能会抛出,可能与此函数的原因相同(原因不是分配)。
  • @digito_evo 因为标准不要求它是noexcept。

标签: c++ c++20 string-view


【解决方案1】:

使用指针可能会导致未定义的行为,这可能会引发异常。例如什么如果s == nullptr 或指向真正的错误?

【讨论】:

  • UB 不等于投掷。 UB不需要扔。 UB与投掷无关。例如,您可以拥有noexcept 接口,该接口允许 UB 用于无效(对于某些无效定义)参数。这个答案是错误的。
  • @Fureeish 但是,如果实现检测到 UB,则允许抛出异常,并且缺少 noexcept 使得这更容易实现。
  • 没错,这就是为什么重复问题中的答案是完整的。 OP 可以扩展这个答案以引入允许抛出自定义异常的实现的概念,但声明 UB 可能等于抛出 对我来说是一个至关重要的过度简化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2016-11-21
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多