#include <string>
#include <iostream>
#include <string_view>
int main()
{
std::string name { "Vivian" };
auto nickname = std::string_view { name }.substr(0, 3);
name.clear();
std::cout << "Hello there, " << nickname << "!\n";
}
which will happily compile, but whose behavior is undefined.`std::string_view` references that copy. `std::string::clear` destroys it, leaving the `std::string_view` dangling.
1. Print the nickname before clearing the name so that nickname is still valid when you print it (swap lines 4 and 5).
2. Make nickname a copy of the first three bytes of name, rather then a reference to the first three bytes of name.
let nickname = String::from(&name[..3]);In C such code would compile, what's worse, it would work and behave correctly most of the time. If your code was more complex (for example using threads) you would get a bug that the code would work fine most of the time, but once in a while it would display garbage.
The `nickname` variable holds onto a reference to the substring of `name`. Subsequently `name` is modified (cleared).
This forces you to think about the behaviour. Should the nickname remain constant even if the backing `name` string changes? Probably yes, so you'd take a copy at that point.