Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 960
Joe Huang Avatar asked Jan 06 '17 19:01

Joe Huang


1 Answers

  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.

like image 107
Nicol Bolas Avatar answered Oct 04 '22 17:10

Nicol Bolas