What is string_view
This is lightweight, non-owning view(pointer) to a const sequence of characters.
[Example] Consider a window in your house, looking at a car parked on the street. We can look through the window and see the car, but
can’t touch or move the car. Your window just provides a view to the car, which is a completely separate object.
It allows you to refer to a part or the entirety of a string without copying the data, which can lead to performance improvements in specific cases
#include <iostream>
#include <string_view>
int main() {
std::string str = "Hello, World!";
std::string_view view(str); // view references the string, no copy is made
std::cout << view; // Outputs: Hello, World!
std::cout << view.substr(0, 5); // Hello
}
Characteristics
-
Read-only: You can only read data through a std::string_view, not modify it.
No copying: Avoids the overhead of copying strings in many cases
create substrings without incurring the cost of allocation or copying data, unlike std::string, which creates a new object
Comparison
string_view vs const string&
| fun(string_view s) | fun(const string& s) | |
|---|---|---|
| Substrings | Can create a view on a substring without copying or allocating new memory. | Requires creating a new std::string for substrings (incurs allocation and copying). |
| Null-Termination | Does not require null-terminated strings (can point to non-null-terminated buffers). | Assumes a valid std::string, which is always null-terminated. |