Skip to content
  • std::string_view · C++

std::string_view

LearnViaNotes @learnvianotes· 2 min read

std::string_view (C++17) is a read-only, non-owning window onto characters: a pointer plus a length. Passing and slicing it never allocates.

Why use it

C++
#include <iostream>
#include <string>
#include <string_view>

std::size_t countVowels(std::string_view text) {       // accepts literals, std::string, substrings…
    std::size_t n = 0;
    for (char c : text) n += std::string_view("aeiou").find(c) != std::string_view::npos;
    return n;
}

int main() {
    std::string s = "education";
    std::cout << countVowels(s) << ' ' << countVowels("sky") << '\n';   // no temporary std::string for "sky"

    std::string_view sv = "  trim me  ";
    sv.remove_prefix(sv.find_first_not_of(' '));
    sv.remove_suffix(sv.size() - sv.find_last_not_of(' ') - 1);
    std::cout << '[' << sv << "] " << sv.substr(0, 4) << '\n';          // substr is O(1): no copy
}
Output
5 0
[trim me] trim
const std::string&std::string_view
Pass a literal "abc"Creates a temporary std::string (may allocate)No allocation
substrCopies → new stringO(1), shares the characters
Owns dataThe referred string doesNever
Null-terminatedYes (c_str())Not guaranteed
Can modify charsNo (const)No

The dangling trap

C++ — view outliving its string
#include <iostream>
#include <string>
#include <string_view>

std::string makeGreeting() { return std::string(40, 'x'); }

int main() {
    std::string_view sv = makeGreeting();   // view into a temporary that dies at the ';'
    std::cout << sv << '\n';                // clang warns (-Wdangling-gsl); at run time: use-after-free
}

When should a function take std::string by value instead of string_view?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report