Clone
gsl::span and std::span
Jordan Maples [MSFT] edited this page 2020-08-28 10:14:28 -07:00

Span

What is span

A span is a view over memory. It does not own the memory and is only a way to access contiguous sequences of objects.

The gsl::span is based on the standardized version of std::span which was added to C++20. Originally, the plan was to deprecate gsl::span when std::span finished standardization, however that plan changed when the runtime bounds checking was removed from std::span's design.

Differences between gsl::span and std::span

The only difference between gsl::span and std::span is that gsl::span strictly enforces runtime bounds checking. Any violations of the bounds check results in termination of the program.

Which version of span should I use?

Use gsl::span if:

  • you want to guarantee bounds safety in your project.
    • All data accessing operations use bounds checking to ensure you are only accessing valid memory.
  • your project uses C++14 or C++17.
    • std::span as it was not introduced into the STL until C++20.

Use std::span if:

  • your project is C++20 and you need the performance offered by std::span.

span_iterator

Like gsl::span, gsl::span's iterators also differ from std::span's iterator in that all access operations are bounds checked.