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.
&a generates a temporary which cannot be bound to a non-const reference.
Moreover your code has several flaws.
1) &a has type int* whereas you are returning by reference i.e int &. The types don't match.
2) Even if you change &a to a in 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
int &x = 5;
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 write
const int &x = 5;
In this case attaching the temporary to a const-reference prolongs its lifetime. It gets destroyed when x gets destroyed.
#include<iostream>
int& fun();
int main()
{
int p=fun();
std::cout<<p;
return 0;
}
int & fun()
{
int a=10;
return a; //Return a not &a
}
The error invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'' is because you are returning&aand nota`.
Above code would compile correctly but it has a serious flaw.
It returns a reference to a temporary stack variable in the function, Once the function returns all the stack variables get destroyed because of stack unwinding, Eventually you are left pointing to a address location that does not contain valid or values you expected.
You should always avoid returning pointers of references to local objects on stack!
The correct way to do this will be:
#include<iostream>
int* fun();
int main()
{
int *p =fun();
std::cout<< *p;
delete p; //delete dynamically allocated memory else memory leak
return 0;
}
int* fun()
{
int *a = new int; //allocate dynamic memory
*a = 10;
return a;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With