I understand that return local variables should not be passed by value. But I am unable to understand why one works, and the other doesnt.
Number 1
void hello(const string& s)
{
cout << "s";
}
int main()
{
hello("Hello World");
return 0;
}
Number 2
const string& returnHello()
{
return "hello world";
}
int main()
{
const string& hh = returnHello();
cout << hh << endl;
return 0;
}
Number 2 gives segmentation fault.
Why is that? As I understand if I return reference of temporary in a const then that should extend the lifetime of that temporary, isnt it?
Can someone help me understand why one works and other doesnt?