Search⌘ K
AI Features

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

Explore how the C++20 stdspan class offers a safer way to handle C-arrays by creating a lightweight, non-owning view over contiguous data. Discover how spans enable passing arrays to functions with size information, improving code clarity and safety while maintaining minimal overhead.

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:

void parray(int * a); // loses size information

If we define our function with a span ...