How to Use string_view in C++: Syntax and Examples
Use
std::string_view to create a lightweight, non-owning reference to a string or part of a string without copying data. It is declared like std::string_view sv = "text"; and can be used to read or pass strings efficiently.Syntax
std::string_view is a class that holds a pointer to a string and its length without owning the string data. You can create it from string literals, std::string, or character arrays.
Basic syntax:
std::string_view sv = "hello";— from string literalstd::string s = "world"; std::string_view sv = s;— from std::stringstd::string_view sv(data, length);— from pointer and length
cpp
std::string_view sv1 = "hello"; std::string s = "world"; std::string_view sv2 = s; const char* data = "example"; std::string_view sv3(data, 4); // "exam"
Example
This example shows how to create std::string_view from different sources and use it to print parts of strings without copying.
cpp
#include <iostream> #include <string> #include <string_view> int main() { std::string_view sv1 = "Hello, world!"; // from literal std::string s = "C++ string"; std::string_view sv2 = s; // from std::string const char* cstr = "example text"; std::string_view sv3(cstr, 7); // first 7 chars std::cout << sv1 << "\n"; std::cout << sv2 << "\n"; std::cout << sv3 << "\n"; return 0; }
Output
Hello, world!
C++ string
example
Common Pitfalls
Beware: std::string_view does not own the string data it points to. If the original string is destroyed or goes out of scope, the string_view becomes invalid and using it causes undefined behavior.
Also, modifying the original string while a string_view exists can cause unexpected results.
cpp
#include <iostream> #include <string> #include <string_view> int main() { std::string_view sv; { std::string temp = "temporary"; sv = temp; // sv points to temp's data } // temp is destroyed here // sv now points to invalid memory // std::cout << sv << "\n"; // Undefined behavior! return 0; }
Quick Reference
std::string_viewis a non-owning view of a string.- It stores a pointer and length, no copying of string data.
- Safe only if original string outlives the view.
- Useful for efficient read-only string access and function parameters.
Key Takeaways
Use std::string_view to refer to strings without copying data for better performance.
Always ensure the original string outlives the string_view to avoid invalid references.
You can create string_view from literals, std::string, or raw pointers with length.
string_view is read-only and does not manage string memory.
Avoid modifying the original string while a string_view exists to prevent bugs.