I’m a little familiar with the std type std::string but I never see std::string_view before. std::string_view is brought by c++17. Now, I see it and wonder if there is some difference between string and string_view. They have almost the same usage. We can assign a constant string to a string variable or a string_view variable:
string s1="aaaaa"; string_view s2="bbbbb";
What is the difference between s1 and s2? Well, you cannot modify the string using the string_view variable:
string_view s1="aaaaa"; string_view s2=s1+"bbbbb";
error C2676: binary ‘+’: ‘std::string_view’ does not define this operator
or a conversion to a type acceptable to the predefined operator
Yes, string_view does not have a + operator to allow you to modify the string it refers to.
But string variable has no such problem:
string s3="bbbb"; string s4=s3+"cccc";
In fact, string_view does not store the string in its own memory, it just refers(points) to the string, but string does store the string in its own memory.
string s1="aaaa"; string s2=s1; string_view s3="bbbbb"; string_view s4=s3;
In the above example, there is only one copy of “bbbbb” in memory(for the constant itself) while there are 3 copies of “aaaa” in memory(one for the constant string, one for s1 and one for s2).
When assigning a string to a string_view variable, the string_view object record the address of the string object and the length of the string. See this example:
string_view s1="aaaaaa"; string_view s2=s1; string s3="bbbbbbb"; s2=s3; s3="sssss"; string s4=s3; cout<<s1<<endl<<s2<<endl<<s3<<endl<<s4<<endl;
The output is:
aaaaaa sssss b sssss sssss
On line 4, the string_view variable s2 saves the address of the string of s3 and its length(7). On next line the string content is modified by s3. So, although we did not modify the content of the string using s2, the string pointed by s2 is still changed(to the what s3 is now) but because s2 records the length of old s3, we still see some remains of the old s3.