What's the difference between passing span<T> and std::array as arguments?

5.5k Views Asked by At

In his C++ Core Guidelines, Bjarne Stroustrup recommends using span when passing arrays by reference. Why not just pass a std::array object?

1

There are 1 best solutions below

3
On
  1. Passing std::array by value would be copying them. The point of gsl::span is that the function taking them is referencing an existing array of data.

  2. gsl::span is capable of taking arrays of runtime-defined sizes. std::array is fixed at compile-time.

  3. gsl::span does not care what type owns the array; it's just a pointer+size. So a span-based interface can be fed data from std::vector, QVector, and many other types. A std::array based interface requires that you use that specific container.