Re: Is this legal? assigning return value to a const ref?
On 2007-10-31 16:26, Jim Langston wrote:
"James Kanze" <james.kanze@gmail.com> wrote in message
news:1193737109.281910.11190@k79g2000hse.googlegroups.com...
On Oct 29, 8:45 pm, flopbucket <flopbuc...@hotmail.com> wrote:
OP here, in bar() it should be a const reference:
std::string foo()
{
std::string xyz = "FOO";
return xyz;
}
void bar()
{
const std::string& s = foo();
// ... use s now
}
It's perfectly legal, but what's the point in using the const
reference (preferably written "std::string const&") rather than
a value?
==================
I tested this, and the output of the following program is indeed
One Two Unknown
#include <vector>
#include <iostream>
#include <string>
std::string Foo( int Val )
{
switch (Val)
{
case 1:
return "One";
break;
case 2:
return "Two";
break;
default:
return "Unknown";
break;
}
}
int main()
{
const std::string& One = Foo(1);
const std::string& Two = Foo(2);
const std::string& Three = Foo(3);
std::cout << One << " " << Two << " " << Three << "\n";
}
My question is, what is the lifetime of the returned string? The lifetime
of the references? I understand that normally the lifetime of a temporary
variable returned by a function is the statement it is called on, yet the
std::strings returned by Foo is beyond this.
Yes, the temporary lives as long as the reference.
Where do things std::strings reside, in what variable? I had always thought
that a reference was just a glorified pointer, but this code seems to
indicate more than this. The compiler seems to treat the std::strings
returned by Foo as being owned by the variables One, Two and Three, even
though they are references.
My guess would be that, since the standard does not talk much about the
implementation of references, in this case the compiler simply creates
three strings on the stack, and the variables One, Two and Three refers
to them. In other words the code generated is the same as though One,
Two, and Three were const strings and not references.
--
Erik Wikstr??m