Modifying Elements Through a Span

If I modify an element through a std::span, does it affect the original data? Can you show an example?

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.

Array Spans and std::span

A detailed guide to creating a "view" of an array using std::span, and why we would want to

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Span vs Vector in C++
When should I use std::span over std::vector in C++? What are the key differences and trade-offs between these two types?
Creating a Span from a Vector
How can I create a std::span from a std::vector in C++? Can you provide an example?
Span Size and Stack Overflow
Is there a limit to the size of a std::span? Could creating a very large std::span lead to a stack overflow?
Lifetime of a Span
What happens if I create a std::span from a vector, and then the vector goes out of scope? Is it safe to continue using the span?
Using Span as a Function Parameter
What are the benefits of using std::span as a function parameter instead of a reference to a container like std::vector or std::array?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant