Search

6.6a — An introduction to std::string_view

In the previous lesson, we talked about C-style strings, and the dangers of using them. C-style strings are fast, but they’re not as easy to use and as safe as std::string.

But std::string (which we covered in lesson S.4.4b -- An introduction to std::string), has some of its own downsides, particularly when it comes to const strings.

Consider the following example:

As expected, this prints

hello hello hello

Internally, main copies the string “hello” 3 times, resulting in 4 copies. First, there is the string literal “hello”, which is known at compile-time and stored in the binary. One copy is created when we create the char[]. The following two std::string objects create one copy of the string each. Because std::string is designed to be modifiable, each std::string must contain its own copy of the string, so that a given std::string can be modified without affecting any other std::string object.

This holds true for const std::string, even though they can’t be modified.

Introducing std::string_view

Consider a window in your house, looking at a car sitting on the street. You can look through the window and see the car, but you can’t touch or move the car. Your window just provides a view to the car, which is a completely separate object.

C++17 introduces another way of using strings, std::string_view, which lives in the <string_view> header.

Unlike std::string, which keeps its own copy of the string, std::string_view provides a view of a string that is defined elsewhere.

We can re-write the above code to use std::string_view by replacing every std::string with std::string_view.

The output is the same, but no more copies of the string “hello” are created. The string “hello” is stored in the binary and is not allocated at run-time. text is only a view onto the string “hello”, so no copy has to be created. When we copy a std::string_view, the new std::string_view observes the same string as the copied-from std::string_view is observing. This means that neither str nor more create any copies. They are views onto the existing string “hello”.

std::string_view is not only fast, but has many of the functions that we know from std::string.

Because std::string_view doesn’t create a copy of the string, if we change the viewed string, the changes are reflected in the std::string_view.

We modified arr, but str appears to be changing as well. That’s because arr and str share their string. When you use a std::string_view, it’s best to avoid modifications to the underlying string for the remainder of the std::string_view‘s life to prevent confusion and errors.

Best practice

Use std::string_view instead of C-style strings.

Prefer std::string_view over std::string for read-only strings, unless you already have a std::string.

View modification functions

Back to our window analogy, consider a window with curtains. We can close either the left or right curtain to reduce what we can see. We don’t change what’s outside, we just reduce the visible area.

Similarly, std::string_view contains functions that let us manipulate the view of the string. This allows us to change the view without modifying the viewed string.

The functions for this are remove_prefix, which removes characters from the left side of the view, and remove_suffix, which removes characters from the right side of the view.

This program produces the following output:

Peach
each
ea

Unlike real curtains, a std::string_view cannot be opened back up. Once you change the visible area, you can’t go back (There are tricks which we won’t go into).

std::string_view works with non-null-terminated strings

Unlike C-style strings and std::string, std::string_view doesn’t use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.

This program prints:

aeiou

Ownership issues

Being only a view, a std::string_view‘s lifetime is independent of that of the string it is viewing. If the viewed string goes out of scope, std::string_view has nothing to observe and accessing it causes undefined behavior. The string that a std::string_view is viewing has to have been created somewhere else. It might be a string literal that lives as long as the program does or it was created by a std::string, in which case the string lives until the std::string decides to destroy it or the std::string dies. std::string_view can’t create any strings on its own, because it’s just a view.

What's your name?
nascardriver
Hello nascardriver
Your name is �P@�P@

When we created str and filled it with std::cin, it created its internal string in dynamic memory. When str goes out of scope at the end of askForName, the internal string dies along with str. The std::string_view doesn’t know that the string no longer exists and allows us to access it. Accessing the released string through view in main causes undefined behavior, which on the author’s machine produced weird characters.

The same can happen when we create a std::string_view from a std::string and modify the std::string. Modifying a std::string can cause its internal string to die and be replaced with a new one in a different place. The std::string_view will still look at where the old string was, but it’s not there anymore.

Warning

Make sure that the underlying string viewed with a std::string_view does not go out of scope and isn’t modified while using the std::string_view.

Converting a std::string_view to a std::string

An std::string_view will not implicitly convert to a std::string, but can be explicitly converted:

This prints:

ball
ball

Converting a std::string_view to a C-style string

Some old functions (such as the old strlen function) still expect C-style strings. To convert a std::string_view to a C-style string, we can do so by first converting to a std::string:

This prints:

ball has 4 letter(s)

However, creating a std::string every time we want to pass a std::string_view as a C-style string is expensive, so this should be avoided if possible.

Opening the window (kinda) via the data() function

The string being viewed by a std::string_view can be accessed by using the data() function, which returns a C-style string. This provides fast access to the string being viewed (as a C-string). But it should also only be used if the std::string_view‘s view hasn’t been modified (e.g. by remove_prefix or remove_suffix) and the string being viewed is null-terminated.

In the following example, std::strlen doesn’t know what a std::string_view is, so we need to pass it str.data():

balloon
7

When a std::string_view has been modified, data() doesn’t always do what we’d like it to. The following example demonstrates what happens when we access data() after modifying the view:

all has 6 letter(s)
str.data() is alloon
str is all

Clearly this isn’t what we’d intended, and is a consequence of trying to access the data() of a std::string_view that has been modified. The length information about the string is lost when we access data(). std::strlen and std::cout keep reading characters from the underlying string until they find the null-terminator, which is at the end of “balloon”.

Warning

Only use std::string_view::data() if the std::string_view‘s view hasn’t been modified and the string being viewed is null-terminated. Using std::string_view::data() of a non-null-terminated string can cause undefined behavior.

Incomplete implementation

Being a relatively recent feature, std::string_view isn’t implemented as well as it could be.

There’s no reason why line 5 and 6 shouldn’t work. They will probably be supported in a future C++ version.


6.7 -- Introduction to pointers
Index
6.6 -- C-style strings

78 comments to 6.6a — An introduction to std::string_view

  • Jean-Paul

    hello, I can't seem to get std::string_view to work at all. I have set my compiler to C++17, and even tried the demo for C++20, it just gives this error :

    Severity    Code    Description    Project    File    Line    Suppression State
    Error (active)    E0135    namespace "std" has no member "string_view"    examples    C:\Users\User\source\repos\examples\examples.cpp    8    

    I have included <string> and <string_view>, created new repos and updated to above C++17 there too.
    Thank you loads in advance!

  • Uyph

    Hi, as far as i'm aware, only std::string and C-style string guarantee null-terminated strings. So how is a string defined with std::string_view is null-terminated like you said here?

  • Hello, I've been experimenting with std::string, and with liberal CPP Reference use, I've coded a text reverser and a pig latin translator. Do these look good to you?

    Text Reverser:

    Pig Latin Translator:

    • nascardriver

      Hello

      Text Reverser
      - You don't need to erase anything. You can almost do `temp += str[count];` and remove the `erase` calls.

      Pig Latin Translator
      - You can do `using std::string;` to use individual namespace members.
      - `sub` potentially overflows. You don't need to store all words or characters.
      - Doing everything in one function makes your code hard to read. Add functions like `isVowel`, `transformWord`, `getNextWord`.
      If you have a `transformWord` function that translates a single word to pig latin, you could use `std::cin`'s space separation behavior to split the input

  • Karl Phazer

    What do you mean by "stored in the binary"? Do you refer to the compiled code file? If so, the strings have to still also be stored somewhere in the memory at least once so the program can use them, right?

    • nascardriver

      Correct. String literals are stored in a section of the binary that gets loaded into memory without doing any modifications to the data. That's the cheapest way of storing values that can't appear in the binary code itself.

  • Karl Phazer

    Thoughts about explicit / implicit type conversion...

    I'm probably just splitting hairs here (and/or maybe this is a borderline case) but in the example below, I would've thought that only the last line would have qualified as an explicit type cast:

    Also, I noticed that a direct initialization (with parentheses) also works while the 'normal' copy initialization (with an equals sign) does not:

    So, this is kind of interesting. If the code in line 2 would compile, would you consider it an implicit conversion?

    • nascardriver

      Only the last one is an explicit cast, but the `std::string` constructor call is also explicit (We're obviously calling `std::string`'s constructor).
      This all gets at `explicit` constructors, which we cover them later in chapter 9. `explicit` constructors disallow copy-initialization, which is why you can't use the equals sign to initialize an `std::string` with a `std::string_view`.

  • Narendra

    Hey Nascardriver,

    Thanks for the good tutorials. Its helping me a lot to get in to the C++.

    I ran the copy of your code related to the ownership issue. But I am able to print name also from the main function. Seems, it does not go out scope here as we are returning it ?
    I even tired with the static array and able to return the string view and print it in the main():

  • DylanM

    Good tutorial, thank you for your great work! However I got a little confused in this one because although you provide good analogies for how a string_view works, I feel like you don't anywhere explicitly define what a string_view is.  One question I had was "can an std::string_view stand on it's own without needing to be assigned an std::string or char array first?" I guess any literal you put in your source code must also have a fixed memory address/value so then that becomes what the string_view is viewing when it gets initialized with a string literal?

    • nascardriver

      Thank you for your feedback!

      I updated section "Introducing std::string_view" and "Ownership issues" to address your questions.

      A `std::string_view` can stand on its own, but only if it's empty

      If no string exists, there's nothing the `std::string_view` can observe.

  • Hi, when I type

    It gives an error : 'string_view' is not a member of 'std'

  • Lucky Abby

    I have an impression that string_view is behave like an alias but with "window view" and nothing else. the most usable is still std::string and if we need to mimic "window view" we can use substring function, please cmiimw

  • sv

    i have read quite a few times now that this thing is faster than that thing, like in this chapter C-style strings are faster than std::string, so my question is how is that decided? what makes one thing faster than other? and faster in what sense?

    • nascardriver

      Faster in runtime. Everything you do at runtime takes up time, for example copying a string or creating a string. Your hardware has to work to make these things happen, and that takes time. When you do these things often enough, the time will become noticeable to a human (For example you might get less fps in a video game, or launching the game takes longer).

  • nascardriver

    `name` is a local variable of `getName`, it dies when `getName` ends. The `std::string_view` views `name`, but doesn't extend its lifetime, so `main` is trying to access a variable that's already dead.

  • Innervate

    In line 12 under the section "std::string_view works with non-null-terminated strings" we do the following:

    what is exactly happening here? I understand that we are initializing str with an array, but I don't quite remember seeing this assigning form.

    • nascardriver

      There are different ways of creating a `std::string_view`, one of them is via a data source and a length. `vowels` is the data source and `std::size(vowels)` is the length. We need the length here, because otherwise `std::string_view` would try to determine the length of `vowels` by searching for the null terminator.

      https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view

  • Taras

    Hi, teachers
    Say I want to get the size (not length) of the C-string using the string_view, but I get the error
    messaging to me "error: no matching function for call to ‘size(const char*&)’" Is there any solution of how to do this? if there will be discussed later in chapters please tell so. Please see the code below

    • nascardriver

      Your question appears to be how to get the length of a C-style string, unrelated to `std::string` and `std::string_view`. If that's not the case, please ask again.

      • Taras

        nascardriver,
        I understood that by help of data() or c_str() function we can convert string_view to C-style string. C - style string is the array of chars that has the '\0' terminated as it was mentioned in 6.6 lesson. Consequently I could get the size of that array by help of std::size (included in iterator library). But then I get the error instead. So I could presume that realString.c_str() reutrns a type that can't be fed into the std::size. Correct my assumptions please to get the better feeling of understanding.

        • nascardriver

          A C-style string is a `const char*` (Remember, arrays like decaying to pointers). It doesn't hold size information, so `std::size` can't do anything with it.

  • buku

    Unlike C-style strings and std::string, std::string_view doesn’t use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.

    and std::string is not null terminated

    • nascardriver

      The internal string of `std::string` can use whatever format it wants. But the internals don't matter in this case. There is no way to access a `std::string` such that it doesn't appear as a null-terminated string.

  • Michael

    What is going on with

    What is the difference between doing std::string{v} and static casting?

  • Nikola

    Hello again,

    Just a minor thing and probably not even that important, but under the section "View modification functions" you include the <cstring> header for the std::strlen function yet it is never used.
    Just my 2c.

    Keep up the good work!

  • fighter_fish

    May be you meant "dependent" instead of "independent" under the Ownership Issues section?

    • nascardriver

      Nope, the `std::string_view`'s lifetime is independent of the string it's viewing. The string could live longer or shorter than the `std::string_view`.

      • JasonA

        I think the combination of that first sentence saying “independent” but then the second sentence explaining how the two are magically intertwined is what is confusing. If the first sentence had an extra “..., but once the original string goes out of scope ..” added to it, then it would be clearer. A std::string_view can’t exist in any meaningful/usable way once the string it is a view for is no longer in scope/existing.

  • Don

    So ...
    1. When modifying a C-style string, the std::string_view which is observing that string will get the changes too.
    2. But when modifying a std::string, the observing std::string_view will somehow causes undefined behavior.
    3. So it is the best to use std::string_view only to observe literal strings.
    Do I understand correctly ?

  • Jimmy Hunter

    I'm a little confused.  The following two teaching points seem to contradict each other on the subject of std::string_view and whether it is a null-terminated string. Can you help please?

    Unlike C-style strings and std::string, std::string_view doesn’t use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.

      // It's okay to use data() because we haven't modified the view, and the
      // string is null-terminated.
      std::cout << std::strlen(str.data()) << '\n';

    Did you mean to write in the commented line that "string is not null-terminated"?

    • nascardriver

      Nope, it's correct as written. Not every `std::string_view` views a null-terminated string. `std::string_view` doesn't modify the string it's viewing. If we initialize it with a string literal (Remember that string literals are null-terminated), then we can safely access `data()`, because it's just a view at out string literal (Which is null-terminated). Though, we have to keep track of this ourselves. If we initialized the `std::string_view` with a char array or let it view only a section of a string, it would not be null-terminated.

  • Bruno

    >>Being only a view, a std::string_view‘s lifetime is independent of that of the string it is viewing. If the viewed string goes out of scope, std::string_view has nothing to observe and accessing it causes undefined behavior.

    Dependent instead of independent ?

    • Alex

      A std::string_view has an independent lifetime from the string it's viewing (e.g. a std::string_view can outlive the string it's viewing, at which point, it becomes invalid).
      A std::string_view validity is dependent on the string it's viewing (e.g. a std::string_view becomes invalid when the string it's viewing dies).

  • Jordy

    std::string_view's function seems to overlap a lot with what constant references are used for. Why is it preferred?

    • nascardriver

      I suppose you mean a const reference to a `std::string`.
      `std::string` can't be used at compile-time, as it requires dynamic memory allocation. Also, if you use a `std::string`, you have to create it first before you can bind a reference to it. Creating the `std::string` creates a copy of the string literal, which might be undesired.

  • kitabski

    Good day everybody!!!
    Wanted to clarify one thing.
    The following code works just fine even though i don't include string or string_view

  • kavin

    Hi,  Under Opening the window (kinda) via the data() function:
    how do we know  std::string_view str{ "balloon" }; is null-terninated string?

    From what i understood is it because all strings(refers to group of characters here) default to null-terminated strings? If the characters are separated by "," they naturally default to non-null-terminated and c-style, which can only be printed to screen by converting them to std::string_view like in vowels example ? Is it correct ?

    • nascardriver

      "balloon" is a string literal, string literals are zero-terminated. If you have an array of characters, then that array isn't zero-terminated (unless you added a terminator).

      • kavin

        Thank you, we add an terminator to array of characters like this right??

        Here it prints 0 after aeiou but its not shown in output right ?

        • nascardriver

          Right. When you print a 0-valued byte, you see nothing. You could print the array without a loop, because now `std::cout` can know where the string ends.

          • giang

            Then, can I ask a C-style string, and string literals are null-terminated, whether string or string_view's variable are not???

            • nascardriver

              It doesn't matter if `std::string` is zero-terminated. The only way to access its internal string is via `.data()` and `.c_str()`, both of which are guaranteed to return a zero-terminated string.
              `std::string_view` is not zero-terminated, because it's just a view onto another string. It has no influence on the string's data, so the only way to reliably know where the string ends is by storing the string's length. This allows `std::string_view` to shrink the viewed string without modifying it (It simply reduces the length).

  • chai

    [code]
    char arr[]{ "Gold" };
    char name[] = "Jason";
    [code]

    I learned in lesson 6.8 that I haven't got '\0' at the end of "Gold" but got one with "Jason". Is the assignment initialisation better?

    • nascardriver

      Both arrays are zero-terminated

      Output
      5
      5

      Lesson 6.6 says so. I couldn't find anything stating the opposite in lesson 6.8. If there's misinformation in lesson 6.8, please point it out as to not confuse other readers.

  • BakaTensi

    So basically, std::string_view is kinda incomplete, and should only be used when we need constant strings at this point if I understand correctly?

  • Vuk

    Hi, I think there is a missing parenthesis in the third code example for the substr call.

  • Wallace

    Minor typo: In "When you use a std::string_view, it’s best to avoid modifications the to underlying string," "the" and "to" seem swapped.

  • Fan

    OK. I saw that the first example has been modified to use char[] instead of const char *, but then should there also be a copy of the string allocated on the stack frame of main()?

    • nascardriver

      Right, I missed that when updating the lesson to use `char[]`, thanks for pointing it out!.

      • Fan

        Then it comes up to 4 copies of the string?

        • nascardriver

          I don't think so. When you have 1 paper and copy it, you have 2 papers but only 1 copy, right?
          The string is there 4 times, but only 3 of the strings are copies. That's how I look at it, I don't know if it's correct.

          • Alex

            In C++, the term "copies" is often used to mean the "number of" something. So if you have a string, and you copy it, you now have two copies of that string.

            I think it's more correct to say that the first program has 4 copies of the string -- but function main only creates 3 of those copies. Perhaps the text should be amended to say, "main creates 3 copies" rather than "this program creates 3 copies"? That way we avoid the ambiguity about whether the string in read-only memory counts as a "copy" or not.

            • nascardriver

              Updated to "main copies the string “hello” 3 times, resulting in 4 copies"

            • Al

              So, just to make it clear: if by "copy" we mean data allocated in the memory, are you saying the first program is using four separate memory locations: one for the literal, one for the char[] and one for each string? Literals use memory?! I don't really undertand how strings hold copies while char[] don't, sorry.

              • nascardriver

                > are you saying the first program is using four separate memory locations: one for the literal, one for the char[] and one for each string?
                Yes.

                > Literals use memory?
                Yes, they have to be stored somewhere.

                > I don't really undertand how strings hold copies while char[] don't
                This should clear up when you learn about pointers. If you still have questions then, just ask.

  • Omar Abdelazeem

    when I'm trying to compile this code , the compiler complain that
    'string_view': is not a member of 'std'

    [/

    #include <iostream>
    #include <string_view>

    int main()
    {
        std::string_view text{ "hello" }; // view the text "hello", which is stored in the binary
        std::string_view str{ text }; // view of the same "hello"
        std::string_view more{ str }; // view of the same "hello"

        std::cout << text << ' ' << str << ' ' << more << '\n';

        return 0;
    }

    ]

  • ErwanDL

    Hey nascardriver,

    From the start of this article, you introduce "const char*" to define strings but I don't think we have already seen what it is and what it does earlier in the tutorial. Is it like using "std::string" ?

    Another thing is I have played around a bit with std::string_view and there are some pretty bizarre behaviours, like in the following code :

    This prints :

    Hello Hello
    Hi Hilo

    What is happening here ? Maybe this could be explained in the article as well ?

    Cheers

    • ErwanDL

      Update : I've advanced to lesson 6.8b and the syntax "const char*" is explained there (C-style string symbolic constants). Maybe this lesson on std::string_view should be moved further down the chapter ?

    • nascardriver

      > you introduce "const char*" to define strings but I don't think we have already seen what it is
      It's a `const char[]` with a different syntax, I though it was a part of the previous lesson, but it isn't. I changed every `const char*` to `char[]` or "C-style string". Thanks for letting me know!

      > like in the following code
      I wanted to include an example that shows that `std::string_view` reflects the changes made to its underlying string, but I'd have to move this lesson further back, which I don't want to do, because it would motivate the use of C-style strings.
      Your code invokes undefined behavior (I added a paragraph to the lesson).
      When you assign "Hi" to `str` in line 8, `str`'s old string "Hello" can be invalidated. In your case, since "Hi" is shorter than "Hello", the `std::string` re-used the memory it was using the store "Hello". That memory is now "Hi\0lo" (\0 is a null-terminator).
      If you assigned something longer, the old string could die completely.
      `view` still looks at where the old string was, but `view`'s size isn't changed (The curtains are where they were before). Since `std::string_view` doesn't use null-terminators, the \0 is ignored and "Hilo" is printed.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]