What is and what is the advantage of using "span<T>"?

Asked

Viewed 60 times

5

C++20 has a new type std::span. External libraries as GSL also provide C++14 and C++17 compliant implementations.

Seeking to understand what a span<T>, I stumbled upon the following definition: A span is a view representing a sequence of contiguous elements in memory. This is a very abstract definition and, at least for a layman in C++, it doesn’t help much to understand what a span<T>.

Trying to understand better what a span<T> found information on some recommended use cases:

1. Central Guidelines of the C++

In Central Guidelines of the C++ span<T> is mentioned several times in rules such as:

I.13: Do not pass arrays as pointers:

Wrong:

void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)

Correct:

void copy(span<const T> r, span<T> r2); // copy r to r2

R.14: Avoid type parameters[], prefer span

Wrong:

void f(int[]);

Correct:

void f(gsl::span<int>);

2. Alternative for type parameters std::array and std::vector

Besides C-style arrays, I have found examples where std::array and std::vector are passed as arguments to functions with type parameters std::span.

Example of the site Modernes C++:

void printMe(std::span<int> container) 
{
    std::cout << "container.size(): " << container.size() << '\n';
    for(auto e : container) std::cout << e << ' ';
    std::cout << "\n\n";
}

int main() 
{   
    std::cout << std::endl;
    
    int arr[]{1, 2, 3, 4};
    printMe(arr);
    
    std::vector vec{1, 2, 3, 4, 5};
    printMe(vec);

    std::array arr2{1, 2, 3, 4, 5, 6}; 
    printMe(arr2);
}

But after all what is the one span<T>? Why should I prefer to use span<T> in place of a pointer, reference to container (e. g., std::vector<int>& refToVector) or std::iterator?

  • Part of my initiative to create more questions for the community. Feel free to answer that question (I shouldn’t answer that question unless the question is open without a valid answer for a long time).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.