Sobes.tech
Junior — Middle

Explain the purpose and main features of std::span in C++.

sobes.tech AI

Answer from AI

std::span in C++ is a lightweight wrapper object that provides contiguous access to a sequence of elements (such as an array or vector) without owning them.

Main features:

  • Does not own memory, only references an existing data block.
  • Allows safe passing of arrays and slices without copying.
  • Supports size and data pointer.
  • Compatible with any containers providing contiguous memory.

Example usage:

#include <span>
#include <vector>
#include <iostream>

void printSpan(std::span<int> s) {
    for (int v : s) {
        std::cout << v << ' ';
    }
    std::cout << '\n';
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4};
    int arr[] = {5, 6, 7, 8};

    printSpan(vec);       // passing a vector
    printSpan(arr);       // passing an array
    printSpan({arr, 3});  // passing a slice of the array
}

std::span is convenient for functions that need to work with sequences of data without copying and without being tied to a specific container.