2

On cppreference there are three overloads for 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)

Why is the third one not marked as noexcept? Similar with std::basic_string_view<CharT,Traits>::ends_with

SherAndrei
  • 528
  • 3
  • 14
  • Third one might fail (UB) for non-nul terminate C-String, allowing exception? – Jarod42 Jan 26 '22 at 12:03
  • 2
    Interesting, the MS implementation is `noexcept` : https://learn.microsoft.com/en-us/cpp/standard-library/basic-string-view-class?view=msvc-170#starts_with – Sean Jan 26 '22 at 12:05
  • @Sean Implementations are allowed to add `noexcept` even if the standard doesn't require it (assuming the function is not specified to throw exceptions): https://eel.is/c++draft/library#res.on.exception.handling-5 – user17732522 Jan 26 '22 at 12:07
  • 3
    @AdrianMole There's a constructor of `std::string_view` that performs dynamic allocation or performs a copy? I hope not. – MatG Jan 26 '22 at 12:07
  • 1
    @MatG Luckily, no. There are however constructors that are potentially throwing, presumably for same reason as this function is (and the reason isn't allocation). – eerorika Jan 26 '22 at 12:09
  • In GCC v11.2, all are `noexcept`. I don't know why it's like that in cppreference. – digito_evo Jan 26 '22 at 12:10
  • 1
    @digito_evo Because the standard doesn't require it to be `noexcept`. – user17732522 Jan 26 '22 at 12:10

1 Answers1

0

Using pointers can potentially result in undefined behavior, that might throw an exception. What e.g. if s == nullptr or pointing to something really wrong?

Chris G.
  • 816
  • 2
  • 15
  • 2
    UB is not equicalent to throwing. UB is not required to throw. UB has nothing to do with throwing. You can have `noexcept` interface that allows UB for an invalid (for some definition of invalid) argument, for example. This answer is wrong. – Fureeish Jan 26 '22 at 12:07
  • 1
    @Fureeish However, an implementation is allowed to throw an exception if it detects UB and the lack of `noexcept` makes this easier to implement. – user17732522 Jan 26 '22 at 12:09
  • 1
    True, that's why the answer in the duplicate question is complete. OP could extend this answer to introduce the concept of an implementation being allowed to throw custom exceptions, but stating that *UB may equal throwing* is a crucial oversimplification for me. – Fureeish Jan 26 '22 at 12:13