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 !
std::string, a temporarystd::stringis creating from the string literal. This temporary is destroyed at the end of the function scope.