Re: Simple question: extending lifetime of temporaries with a reference
On 10 Nov., 03:01, Alan McKenney <alan_mckenn...@yahoo.com> wrote:
My impression is that if you do, say:
// sample 1
std::string str1( "String 1\n");
std::string str2( "string 2\n");
std::string &str_sum = str1 + str2;
std::cout << str_sum << str::endl;
then the temporary object "str1 + str2" won't be destroyed
until str_sum goes out of scope.
Old compilers still might accept this. But it's not exactly well-
formed code. You need to write
std::string const& str_sum = str1 + str2;
But you're right. The life-time of this temporary is extended to that
of the reference. This rule only applies to "local" temporary objects.
operator+(string,string) returns a string object by value which will
be a local temporary object. The compiler will know exactly what it is
and where it is located (automatic memory) -- and even call the right
destructor for you in case you do something like this:
Derived f();
void g() {
BaseClass const& obj = f();
}
On the other hand, I'm fairly convinced that
// sample 2
std::string &f() { std::string temp( "temp value"); return temp; }
void g() {
std::string &ret_val = f();
std::cout << ret_val << std::endl;
}
won't work.
Right. It's not a "local" temporary. The function returns a reference
which could be anything (including a reference to a heap-allocated
object). Defining such a function is not ill-formed but a good
compiler should warn you about it. G++ says: "warning: reference to
local variable is returned".
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]