Search code examples
c++c++17stdstringstring-view

Can I change a std::string, which has been assigned to a std::string_view


I just knew that C++17 introduced std::string_view. It doesn't hold any string, instead, it points to a string. If so, I'm confused by the case below:

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

I just tried the piece of code on some c++17 compiler online, here is the output:

abc
1c

Obviously, 1c is not what I expected.

So does it mean that we shouldn't change the string which has been assigned to a std::string_view?


Solution

  • In general, you shouldn't, as it is fragile.
    Anyway:

    You may change the data behind a reference (a std::string_view is a reference to a string-segment, not to a string like std::string, consisting of start and length), just be aware that you did and how you did it.
    Though refrain from deallocating it, using dangling references is bad.

    std::string doesn't reallocate if the new value fits the current capacity and there is no move-assignment, or both are in SBO-mode.
    In your example, all three are true.

    The only problem is that the data beyond the string-terminator is indeterminate after the assignment, though it is not explicitly overwritten, thus staying c for efficiency.