Given the following code we can see that std::string_view is invalidated when string grows beyond capacity (here SSO is in effect initially then contents are put on the heap)
#include <iostream>
#include <cassert>
#include <string>
using std::cout;
using std::endl;
int main() {
std::string s = "hi";
std::string_view v = s;
cout << v << endl;
s = "this is a long long long string now";
cout << v << endl;
}
output:
hi
#
so if I store a string_view to a string then change the contents of the string I can be in big trouble.
Would it be possible, given the existing std::string implementations to make a smarter string_view? which would not face such a drawback? We could store a pointer to the string object itself and then determine if the string is in SSO more or not and work accordingly.(Not sure how this would work with literal strings though, so maybe that is why it was not done this way?)
I am aware that string_view is akin to storing the return value of string::c_str() but given we have this wrapper around std::string I do not think this gotcha would occur to a lot of people using this feature. Most disclaimers are to make sure the pointed to std::string is within scope but this is a different issue altogether.
std::string const &already exists.string_viewis.string_viewlike class that would survive changes to the string except when the string shrinks too much. There is no way to keep a view of the string from char 10-20 alive when you shrink the string to 5 chars.