std::string_view (C++17)

Non-owning string reference

Interview Relevant: Modern C++ optimization

std::string_view

A lightweight, non-owning view into a string (C++17).

Code Examples

string_view for efficient string passing.

cpp
1#include <string_view>
2
3// Create from various sources
4string_view sv1 = "Hello";           // From literal
5string str = "World";
6string_view sv2 = str;               // From std::string
7
8// No copies made - just a view!
9void printView(string_view sv) {
10    cout << sv << endl;
11}
12printView("Hello");   // No allocation
13printView(str);       // No copy
14
15// Substring without allocation
16string_view sub = sv1.substr(0, 3);  // "Hel"
17
18// Access
19char first = sv1[0];
20char last = sv1.back();
21
22// Warning: string_view doesn't own data!
23string_view dangerous() {
24    string temp = "temp";
25    return temp;  // DANGLING! temp destroyed
26}
27
28// Use for function parameters when you don't need ownership
29bool startsWith(string_view str, string_view prefix) {
30    return str.substr(0, prefix.size()) == prefix;
31}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In