Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it fair to purposefully cause undefined behaviour? [closed]

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?

like image 689
Joseph Mansfield Avatar asked Jan 30 '26 02:01

Joseph Mansfield


1 Answers

When is it fair to purposefully cause undefined behaviour?

Assuming you're asking this from the point of view of a library implementer: whenever you warn your client that failing to comply with the pre-conditions of a given function causes Undefined Behavior, and your client breaks those pre-conditions.

The C++11 Standard Library defines a lot of such functions: just think of the subscript operator for sequence collections.

If you're asking this from the viewpoint of an application programmer, on the other hand, the answer is of course "never", unless you are writing non-portable code that relies on some documented extension of your compiler and/or on some functionality of your Operating System (but then it's arguable whether you are still "talking C++").

Should a library developer feel bad for allowing this or not?

If that was the case, mr. Stepanov should feel horrible by now. No, it is not bad, it just depends on whether your library is designed for maximum efficiency or for maximum safety - with a lot of nuances in the middle.

like image 104
Andy Prowl Avatar answered Jan 31 '26 18:01

Andy Prowl