Change std::string assigned to std::string_view?

Does Modifying a String Affect a std::string_view Pointing to It?

C++17 introduced the std::string_view type, which does not hold its own string, but instead points to a string elsewhere.

To understand the behavior of std::string_view, consider the following code:

std::string str = "abc";
std::string_view strV = str;
std::cout << strV << std::endl;
str = "1";
std::cout << strV << std::endl;

When run on a C++17 compiler, the output is:

abc
1c

This suggests that modifying the string that a std::string_view points to affects the std::string_view. Therefore, we should not change the string a std::string_view is pointing to.

Yes, modifying the string that a std::string_view points to does affect the std::string_view. In the example you provided, when you modify the str string to “1”, the strV string view still points to the same memory location. As a result, the std::string_view still “sees” the modified string and prints “1c” instead of “abc”.

So, to ensure the correctness of your program, you should avoid modifying the string that a std::string_view points to.