Array Spans and std::span

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?

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved