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
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. |