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.