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?
std::array is movable only if its contained objects are movable. std::array is quite different from the other containers because the container object contains the storage, not just pointers into the heap. Moving a std::vector only copies some pointers, and the contained objects are none the wiser.
std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.
std::array<std::vector<int>,3> is the type you want. std::vector is a dynamicly sized array. this creates a 3 "major" element array of 22 "minor" size.
std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.
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 callingfront()
orback()
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 notnoexcept
, even when they are not specified to throw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With