Use the New Span Class to Make Our C-Arrays Safer

Learn to use the new span class to make our C-arrays safer.

We'll cover the following

New for C++20, the std::span class is a simple wrapper that creates a view over a contiguous sequence of objects. The span doesn't own any of its own data, it refers to the data in the underlying structure. Think of it as string_view for C-arrays. The underlying structure may be a C-array, a vector, or an STL array.

How to do it

We can create a span from any compatible contiguous-storage structure. The most common use case will involve a C-array. For example, if we try to pass a C-array directly to a function, the array is demoted to a pointer and the function has no easy way to know the size of the array:

Get hands-on with 1200+ tech skills courses.