FAQ 32.07 Is it safe to bind a reference variable to a temporary object?

Yes, as long as that reference isn't copied into another reference or pointer.

In the following example, an unnamed temporary string object is created at line 1. A (const) reference (main()'s x) is bound to this temporary. The language guarantees that the unnamed temporary will live until the reference x dies, which in this case is at the end of main(). Therefore, line 2 is safe: the compiler isn't allowed to destruct the unnamed temporary string object until line 3.

 #include <iostream> #include <string> using namespace std; string createTemp() { return "fred"; } int main() {   const string& x = createTemp();                    <-- 1   cout << "x = " << x << "\n";                       <-- 2 }                                                    <-- 3 

(1) Line 1: Reference bound to temporary

(2) Line 2: This is safe

(3) Line 3: Temporary destructed here

There is a caveat don't copy reference x into a pointer variable that's out of the scope in which the temporary was created. For a subtle example of this, see the next FAQ.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net