24

I'm new to the use of the noexcept specifier and I do not understand why std::array::front and std::array::back are not declared noexcept (whereas std::array::begin and std::array::end are).

What is the reason of that?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • 1
    Good question. They would have to be conditionally noexcept on the array size being non-zero. But vendors can strengthen noexceptness as QoI... – Kerrek SB Sep 17 '15 at 16:45
  • @KerrekSB Not even conditionally as `std::array` could be specialized to not have those `noexcept` contrary to `std::array`. Unfortunately the standard does not provide that. – edmz Sep 17 '15 at 17:36

1 Answers1

15

From cppreference

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

So since we can have a 0 sized array front() and back() could cause an exception

To quote Sebastian Redl on why the standard doesn't mandate operator[], front and back be marked noexcept

The standard's policy on noexcept is to only mark functions that cannot or must not fail, but not those that simply are specified not to throw exceptions. In other words, all functions that have a limited domain (pass the wrong arguments and you get undefined behavior) are not noexcept, even when they are not specified to throw.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 9
    But that's a static condition, so the `noexcept` could be conditional (just like `vector`'s default constructor). – Kerrek SB Sep 17 '15 at 16:45
  • @KerrekSB [Maybe relevant?](http://webcache.googleusercontent.com/search?q=cache:hEGrzM8rlE0J:gcc.gnu.org/ml/gcc-patches/2013-09/msg01397.html+&cd=1&hl=en&ct=clnk&gl=pl) – набиячлэвэли Sep 17 '15 at 16:46
  • @KerrekSB Added to the answer. let me know if that is enough. – NathanOliver Sep 17 '15 at 16:58
  • 1
    @NathanOliver That doesn’t really answer Kerrek’s concern: on a nonzero `array`, `front` and `back` cannot fail. This is known at compile time (since the array size is known at compile time), hence these functions could be `noexcept`, even accounting for the quote you added. – Konrad Rudolph Sep 17 '15 at 17:00
  • 5
    None of your answer is relevant. This isn't about narrow contracts. `std::array` is not a dynamic container. – Kerrek SB Sep 17 '15 at 17:09