std::string_view — lightweight, non-owning reference to a string. Avoids copies.
1#include <string_view>23// Takes string_view — works with string, const char*, literals4std::string_view process(std::string_view sv) {5 return sv.substr(0, 5);6}78std::string s = "Hello, World!";9std::string_view sv1 = s; // From string10std::string_view sv2 = "literal"; // From literal11std::string_view sv3 = s.data(); // From char*1213std::cout << sv1.substr(0, 5); // "Hello"14std::cout << sv1.size(); // 1315std::cout << sv1[0]; // H1617// Comparison18if (sv1 == "Hello, World!") { /* ... */ }1920// Convert back to string (when needed)21std::string str(sv1);
Caveats: