3

When compiling the following code the compiler issue the warning warning: returning reference to temporary

const string& example1()
{
    return "Hello";
}

This code does not even compile:

void example2(){
    const string& str = "Hello";
}

and this one is valid since we know that a literal string is initialized into read-only memory segment by the compiler.

char* example3()
{
    return "Hello";
}

Could you please help me understand what happen behind the scene when compiling the method example1() ?

Thank you very much for your help !

2
  • Since the method return an std::string, a temporary std::string is creating from the string literal. This temporary is destroyed at the end of the function scope. Commented Feb 1, 2015 at 4:34
  • example2 is working well for me. godbolt.org/z/jLFexp Commented Nov 7, 2018 at 18:41

2 Answers 2

4

Return "Hello" creates a temporary std::string which will be deleted at the end of your function. Here, you are returning a reference on a std::string that won't exist at the end of the function call.

To solve that you can change the return type of example1() to string

Sign up to request clarification or add additional context in comments.

2 Comments

Preferably just string without const.
Thank you very much Jerome and Zenith. But how come then a temporary string is not created in the case of example2() ?
2

Adding to Jerome's answer, you can also do this if you only want to have a single copy of the string:

const string& example1()
{
    static string example = "Hello";
    return example;
}

(Now example is a static function variable, and will also exist outside the function.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.