Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning temporary object and binding to const reference [duplicate]

Possible Duplicate:
Does a const reference prolong the life of a temporary?

My compiler doesn't complain about assigning temporary to const reference:

string foo() {   return string("123"); };  int main() {   const string& val = foo();   printf("%s\n", val.c_str());   return 0; } 

Why? I thought that string returned from foo is temporary and val can point to object which lifetime has finished. Does C++ standard allow this and prolongs the lifetime of returned object?

like image 792
gruszczy Avatar asked Jul 19 '12 11:07

gruszczy


People also ask

Does const reference make a copy?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .

Is temporary object created in return by reference?

Explanation: A temporary object is created when an object is returned by value. The temporary object is used to copy the values to another object or to be used in some way. The object holds all the values of the data members of the object.

Can a const function return a reference?

Then, no, you can't do that; in a const method you have a const this pointer (in your case it would be a const Foo * ), which means that any reference you can get to its fields1 will be a const reference, since you're accessing them through a " const path".

Can you change the value of const reference?

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.


1 Answers

This is a C++ feature. The code is valid and does exactly what it appears to do.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by foo() lives until the closing curly brace.

P.S: This only applies to stack-based references. It doesn’t work for references that are members of objects.

Full text: GotW #88: A Candidate For the “Most Important const” by Herb Sutter.

like image 194
Sergey K. Avatar answered Oct 12 '22 07:10

Sergey K.