In several recent conference presentation I've heard Bjarne Stroustrup and others mention new coding guidelines for C++ and some types supporting them.
Specifically, I remember the example of span<T>
instead of (T* p, int n)
as a parameter to a function (at time about 32:00 into the talk); but I also remember the suggestion to use array_view<T>
. Are they two alternatives but the same concept? Or am I confusing things and they're actually not so related?
I can't seem to find any authoritative definition of what they're both supposed to be about.
gsl::span is a replacement for (pointer, length) pairs to refer to a sequence of contiguous objects. It can be thought of as a pointer to an array, but that knows its bounds. For example, a span<int,7> refers to a sequence of seven contiguous integers. A span does not own the elements it points to.
array_view. This class implements a view in to a range of a C array, etl::array, std::array, etl::vector and std::vector. It will support. construction from any class that supports data() and size() member functions as well as plain C arrays.
A std::span stands for an object that can refer to a contiguous sequence of objects. A std::span, sometimes also called a view, is never an owner. This contiguous memory can be a plain array, a pointer with a size, a std::array, a std::vector, or a std::string.
A span provides a safe way to iterate over and index into objects that are arranged back-to-back in memory. Such as objects stored in a built-in array, std::array , or std::vector . If you typically access a sequence of back-to-back objects using a pointer and an index, a span is a safer, lightweight alternative.
We talked with people in the library working group in the standards committee. They wanted the array_view
they are trying to get into the standard to be read only. For the core guidelines, we needed an abstraction that was read and write. To avoid a clash between the (potential) standards and the guidelines support library (GSL), we renamed our (read and write) array_view
to span
: https://github.com/microsoft/gsl .
In the CppCoreGuidlines The original array_view
was renamed to span
.
See: https://github.com/isocpp/CppCoreGuidelines/pull/377
It is described thus:
span is a bounds-checked, safe alternative to using pointers to access arrays
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With