How do I bridge to legacy arrays and pointers with std::span?

In modern C++, std::span is an excellent way to bridge the gap between legacy arrays and pointers, providing a safer and more convenient way to work with contiguous sequences of elements. This flexibility allows developers to interact with legacy C-style arrays while maintaining the benefits of modern C++ constructs.

std::span is a lightweight, non-owning view into a sequence of elements, which can be especially useful when dealing with legacy code. Below is an example demonstrating how to create a std::span from a legacy C-style array, as well as from a pointer and size.

#include #include void processSpan(std::span s) { for (int num : s) { std::cout << num << " "; } std::cout << std::endl; } int main() { int legacyArray[] = {1, 2, 3, 4, 5}; std::span spanFromArray(legacyArray); // Create a span from a C-style array processSpan(spanFromArray); int* legacyPointer = new int[5]{6, 7, 8, 9, 10}; std::span spanFromPointer(legacyPointer, 5); // Create a span from a pointer and size processSpan(spanFromPointer); delete[] legacyPointer; // Don't forget to clean up return 0; }

C++ std::span legacy arrays pointers modern C++ safe code non-owning view contiguous sequences