Plz explain difference between functions returning ref
Check out this example:
Code:
#include <iostream>
class foo{
};
foo& fn1(){
foo f;
return f;
}
foo& fn2(){
foo* f_ptr = new foo();
return *f_ptr;
}
int main(){
foo& f_ref = fn1(); // Compiler warning here
foo& f_ref2 = fn2();
return 0;
}
When I compile this, I only get the warning for "reference to local variable 'f' returned" when fn1() is called.
What's the difference between fn1() and fn2(), besides the obvious use of a foo pointer in fn2()?
Why do I only get the warning for fn1()?
Isn't fn2() returning a reference to a local variable as well?