std::string_view (C++17)
Non-owning, read-only string references
The Problem
Before C++17, passing strings to functions required choosing between const char* (no size), const std::string& (requires conversion), or std::string (copies).
// Old ways: problematic
void process_cstr(const char* str); // No size info
void process_string(const std::string& s); // Requires std::string
// Problems:
process_string("hello"); // Creates temporary std::string
// std::string_view solves this
#include <string_view>
void process(std::string_view sv); // Works with all string types
// Usage - no allocations!
process("hello"); // C string literal
process(std::string("hello")); // std::string
process(some_string_view); // Another string_viewKey Features
std::string_view sv = "Hello, World!";
// O(1) operations
size_t len = sv.size(); // Length
bool empty = sv.empty(); // Check if empty
char c = sv[0]; // Index access (no bounds check)
char safe = sv.at(0); // Safe access with bounds check
// Creating subviews - O(1), no copy
auto sub = sv.substr(0, 5); // "Hello"
// Compare
if (sv == "Hello, World!") { }
// Find
size_t pos = sv.find("World");Best Practices
- ✓Use std::string_view for read-only string parameters
- ✓Pass by value (cheap to copy, like a pointer + size)
- ✗Never store string_view as member variable (dangling risk)
- ✗Don't use after the source string has been destroyed