Array Spans and std::span

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?

Abstract art representing computer programming

The main differences between std::span and std::vector are:

Ownership

std::vector owns the elements it contains. It manages the memory allocation and deallocation for those elements.

std::span does not own the elements it references. It simply provides a view into a contiguous sequence of elements stored elsewhere.

Size

The size of a std::vector can change dynamically at runtime. Elements can be added or removed from a vector.

The size of a std::span is fixed at the time it is created. A span cannot change the number of elements it references.

Memory Allocation

std::vector allocates its own memory to store elements. This allocation happens on the heap.

std::span does not allocate any memory. It simply holds a pointer to elements stored elsewhere, either on the stack or the heap.

Cost of Copying

Copying a std::vector is an expensive operation because it involves allocating new memory and copying all the elements.

Copying a std::span is cheap, it only involves copying a pointer and a size.

You should use std::span when you want a lightweight, non-owning view into a sequence of elements, and you don't need to change the size of that sequence. This is often useful for passing arrays to functions:

#include <span>
#include <vector>

void Process(std::span<const int> data) {
  for (int i : data) {
    // Process each element
  }
}

int main() {
  std::vector<int> v{1, 2, 3, 4, 5};
  Process(v);
}

Use std::vector when you need ownership of the elements, or when you need to be able to change the number of elements dynamically.

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