What is std::span in C++ and when should it be used?
Hello colleagues! I've been writing in C++ for about a year, but I constantly face the problem of passing arrays and buffers to functions. Usually I pass a pointer to the first element and the size separately, but this looks cumbersome and error-prone. For example:
```cpp
void process_data(int* arr, size_t size) {
for (size_t i = 0; i < size; ++i) {
// do something with arr[i]
}
}
int main() {
int data[] = {1, 2, 3, 4, 5};
process_data(data, 5); // works, but easy to make a mistake with size
process_data(data, 100); // undefined behavior, error!
}
```
Recently I came across `std::span` in C++20. I read the documentation, but I don't fully understand how it's better than a regular pointer + size. It seems like it's just a "view" on an array. Why is it needed? When should it be used instead of a simple pointer and size?
No answers yet.
Log in to leave an answer