FAQ 32.08 Should a parameter passed by const reference be returned by const reference?

FAQ 32.08 Should a parameter passed by const reference be returned by const reference?

No; it might create a dangling reference, which could destroy the world.

Returning an object by reference is not dangerous in and of itself, provided that the lifetime of the referent exceeds the lifetime of the returned reference. This cannot be guaranteed when a const reference parameter is returned by const reference, because the original argument might have been an unnamed temporary.

In the following example, an unnamed temporary string object is created at line 1. Parameter x from function unsafe() is bound to this temporary, but that is not an explicit, local reference in the scope of main(), so the temporary's lifetime is governed by the usual rules the temporary dies at the ; of line 1. Unfortunately, function unsafe() returns the reference x, which means main()'s y ends up referring to the temporary, even though the temporary is now dead. This means that line 2 is unsafe: it uses y, which refers to an object that has already been destructed a dangling reference.

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

(1) Line 1

(2) Line 2: BOOM!

Note that if a function accepts a parameter by non-const reference (for example, f(string& s)), returning a copy of this reference parameter is safe because a temporary cannot be passed by non-const reference.



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