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?
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 .
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.
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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With