Why do I get Segmentation fault
with the code below?
#include <iostream>
#include <string>
const std::string& f() { return "abc"; }
std::string&& g() { return "xyz"; }
int main()
{
const std::string& s1 = f();
std::string&& s2 = g();
s2 += "-uvw";
std::cout << s1 << ", " << s2 << std::endl;
return 0;
}
I expected that both s1
and s2
are still alive with I print them, but actually they are not. Why?
For example, they are alive in the code below that does not crash:
#include <iostream>
#include <string>
int main()
{
const std::string& s1 = "abc";
std::string&& s2 = "xyz";
s2 += "-uvw";
std::cout << s1 << ", " << s2 << std::endl;
return 0;
}
what is the difference?