The standard library habitually allows for undefined behaviour if you break any requirements on template types, give erroneous function arguments, or any other breach of contract. Is it considered a good practise to allow this in user libraries? When is it fair to do so?
Consider writing an operator[]
for a container:
template <typename t>
T& container<T>::operator[](int i)
{
return internal_array[i];
}
If i
indexes outside the bounds of the internal_array
, we hit undefined behaviour. Should we allow this to happen or do bounds checking and throw an exception?
Another example is a function that takes an int
argument but only allows a restricted domain:
int foo(int x)
{
if (x > 0 && x <= 10) {
return x;
}
}
If x
is not within the domain, execution will reach the end of the function without a return
statement - this gives undefined behaviour.
Should a library developer feel bad for allowing this or not?