Possible Duplicate:
return type in c++
#include<iostream>
int& fun();
int main()
{
int p=fun();
std::cout<<p;
return 0;
}
int & fun()
{
int a=10;
return &a;
}
why does this code give error as,error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'..Actually i am not clear about the temporaries i.e. when are they created and when are they get destroyed.?so ,please explain temporaries to some extent too.
&agenerates a temporary which cannot be bound to a non-const reference.Moreover your code has several flaws.
1)
&ahas typeint*whereas you are returning by reference i.eint &. The types don’t match.2) Even if you change
&atoain the return statement you code still won’t work because returning a local variable by reference and then using the result is UB.Invalid initialization of non-const reference from a temporary
C++ doesn’t allow temporaries to be bound to non constant references.
For example you can’t do something like this
because the temporary
int(5)would be destroyed at the end the expression which it is a part of. However references to const can be initialized from a temporary i.e you can safely writeconst int &x = 5;In this case attaching the temporary to a const-reference prolongs its lifetime. It gets destroyed when
xgets destroyed.