std::string_view
and std::span
are both lightweight, non-owning views over a sequence of elements, but they serve different purposes and have different use cases.
std::string_view
std::string
, C-style strings, and string literals.Example:
#include <iostream>
#include <string_view>
int main() {
std::string_view view{"Hello, world"};
std::cout << view;
}
Hello, world
std::span
const
).Example:
#include <iostream>
#include <span>
void printSpan(std::span<int> s) {
for (int i : s) {
std::cout << i << ' ';
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::span<int> sp{arr};
printSpan(sp);
}
1 2 3 4 5
std::string_view
is specialized for strings, while std::span
is generalized for any type of sequence.std::string_view
is read-only, whereas std::span
can be mutable or immutable depending on its type.std::span
provides more general functionality like iterating over elements of any type, while std::string_view
includes string-specific methods like substr()
.std::string_view
when working specifically with strings and need a read-only view.std::span
when you need a view over any contiguous sequence of elements and might need to modify the elements.Both types improve performance by avoiding unnecessary copies and providing safe access to sequences, but they cater to different needs.
Answers to questions are automatically generated and may not have been reviewed.
A practical introduction to string views, and why they should be the main way we pass strings to functions