Back to questions
JuniorDebuggingCommon
What happens when you build and run this program?
#include <iostream>
#include <string>
#include <string_view>
std::string make_name() {
return "Ada";
}
int main() {
std::string_view name = make_name();
std::cout << name << '\n';
}Undefined behavior: the temporary string is destroyed right after name is declared
- Expecting
Adabecause the view keeps the string alive: a view only looks at characters it does not own; those are destroyed, so readingnameis undefined behavior. - Expecting
string_viewto copy the characters: it stores only the address of the first character and the length, and the characters died with the temporary.
- Why is
const std::string& name = make_name();safe while thestring_viewis not? - When is
std::string_viewa better parameter type thanconst std::string&?
Fix
name looks at the characters of a temporary string, and that string is destroyed right after name is declared. Store the result in a std::string: such a variable owns its characters and lives until the end of main.
#include <iostream>
#include <string>
std::string make_name() {
return "Ada";
}
int main() {
std::string name = make_name();
std::cout << name << '\n'; // Ada
}