Re: Returning a reference to a temporary object
Catalin Pitis wrote:
Hi *
I have a piece of code looking like this:
#include <iostream>
#include <string>
using namespace std;
string foo()
{
return "Something";
}
int main( int, char*[])
{
const std::string& value = foo(); // This is the interest point
/// do something here....
return 0;
}
I've tested the code with MS VC 8.0 and it seems that allows me to hold
a const reference to a temporary object without crashing (both debug
and release targets).
However, is this allowed, according to the standard? Can I use it like
this?
Thanks
Catalin
It's safe since value is actully copy-constructed there.
Another story would be if 'foo' were defined to return a reference:
std::string& foo()
{
std::string str("something");
return str;
}
Here str's destructor is called before the value is initialized, thus
you'd have problems here.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]