Use std::span Instead of C-style Arrays -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGC-style arrays are still used, mostly when you have to deal with C-libraries. They come with significant limitations, particularly when passed to functions where array decay occurs, leading to the loss of size information.

Use std::span Instead of C-style Arrays

by Sandor Dargo

From the article:

While reading the awesome book C++ Brain Teasers by Anders Schau Knatten, I realized it might be worth writing about spans.

std::span is a class template that was added to the standard library in C++20 and you’ll find it in the <span> header. A span is a non-owning object that refers to a contiguous sequence of objects with the first sequence element at position zero.

In its goal, a span is quite similar to a string_view. While a string_view is a non-owning view of string-like objects, a span is also a non-owning view for array-like objects where the stored elements occupy contiguous places in memory.

While it’s possible to use spans with vectors and arrays, most frequently it will be used with C-style arrays because a span gives you safe access to its elements and also to the size of the view, something that you don’t get with C-style arrays.

When and why does it come in handy?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.