0

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?

Kraken
  • 23,393
  • 37
  • 102
  • 162
  • The string is already gone when you finish `returnHello` function. – Yksisarvinen Feb 20 '19 at 14:45
  • @Yksisarvinen then why does it work in the first case. Why isnt the case, when we are passing the "Hello World" to function. – Kraken Feb 20 '19 at 14:47
  • 1
    Returning by value is always correct. Returning a reference to a local value not so much. – Michael Surette Feb 20 '19 at 14:48
  • 1
    In the first example the temporary `std::string` object used in the call will have a life-time all through the function. In the second example that temporary `std::string` objects is destructed as soon as the call is ended. – Some programmer dude Feb 20 '19 at 14:48
  • The first example doesn't extend the lifetime of the temporary. That temporary will naturally exist until the end of the expression, which will be after the function returns. – François Andrieux Feb 20 '19 at 14:50
  • "I understand that return local variables should not be passed by value" do you mean "local variables should not be returned by reference" ? As written this, sorry, does not make much sense – 463035818_is_not_an_ai Feb 20 '19 at 15:32

0 Answers0