Undefined Behavior in the STL - Sandor Dargo - CppCon 2022

Discover the perils of undefined behavior in the C++ Standard Template Library (STL) and learn how to avoid it with expert insights and best practices for writing reliable C++ code.

Key takeaways
  • Undefined behavior is a common issue in C++ and can be caused by numerous factors, including undefined behavior in the standard library (STL) and undefined behavior in the program itself.
  • The STL is a set of different headers and template classes and functions that provide solutions to common problems through four building blocks: containers, algorithms, iterators, and function objects.
  • The three main categories of undefined behavior in C++ are: undefined behavior, implementation-defined behavior, and unspecified behavior.
  • Undefined behavior can be caused by attempting to access an out-of-bounds index of a container, using an iterator that has already been invalidated, or attempting to iterate over an array that has already been destroyed.
  • The C++ standard does not specify what should happen in cases of undefined behavior, leaving it up to the compiler implementer to decide what the behavior should be.
  • Undefined behavior can sometimes be caught by compiler warnings or runtime checks, but in many cases it will result in unpredictable behavior, including segmentation faults, runtime errors, or incorrect results.
  • It is generally a good idea to avoid undefined behavior and to follow best practices for writing reliable and maintainable C++ code.
  • Ranges are a new feature in C++ that provide a way to work with sequences of values without having to write loops or iterators.
  • The C++ standard library is designed to be flexible and allow for flexible use, which can sometimes lead to undefined behavior.
  • Implementers of the standard library have a certain level of freedom when it comes to implementing the library, which can sometimes lead to different behavior between different compilers.
  • Undefined behavior is not the same as implementation-defined behavior, which is behavior that is not specified by the standard but is defined by the implementer.
  • The STL provides many algorithms and containers that can be used to solve a wide range of problems, but it is up to the programmer to use them correctly and avoid undefined behavior.