Yes, modifying an element through a std::span
directly modifies the original data. This is because a std::span
provides a view into the original data, it does not create a copy.
Here's an example:
#include <iostream>
#include <vector>
#include <span>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
std::span<int> span{vec};
span[2] = 42;
std::cout << "vec[2]: " << vec[2] << "\n";
std::cout << "span[2]: " << span[2] << "\n";
}
vec[2]: 42
span[2]: 42
In this code, we create a std::vector<int>
called vec
and a std::span<int>
called span
that spans vec
.
We then modify the third element of span
(index 2), setting it to 42. When we print out the third element of both vec
and span
, we see that both have been modified.
This behavior is a key feature of std::span
. It allows you to work with and modify data without the overhead of copying or allocating new memory.
However, this also means you need to be careful when passing spans around. If a function modifies elements through a span, those modifications will be seen by any other code that has access to the original data.
If you want to prevent modifications to the original data through a span, you can create a std::span<const T>
 instead:
std::vector<int> vec{1, 2, 3, 4, 5};
std::span<const int> span{vec};
// Compiler error
span[2] = 42;
A std::span<const int>
allows reading elements but not modifying them, providing a read-only view into the original data.
Answers to questions are automatically generated and may not have been reviewed.
std::span
A detailed guide to creating a "view" of an array using std::span
, and why we would want to