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?
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.
Array Spans and std::span
A detailed guide to creating a "view" of an array using std::span, and why we would want to