for example this function f defined like this :
int f(int x){return x;}
as you know You cant assign a reference to this temporary int :
int& rf=f(2);// this will give an error
but if I redefined my function f like this:
int& f(int x){return x;}
f(2);// so now f(2) is a reference of x, which has been destroyed
so my question is : how can the compiler not let you create a reference to a temporary which will be destroyed after the statment (int the 1st case). and on the other hand it lets you create a reference f(2) to x while compiler knows that this one will be destroyed after return.
Returning a reference to a local is something that can be difficult or impossible for the compiler to detect. For example:
Even without calling external functions, it can still be difficult to analyse a complex program flow to tell whether the returned reference is to a local; rather than trying to define what counts as “simple enough” to diagnose, the standard doesn’t require a diagnostic – it just states that it gives undefined behaviour. A good compiler should give a warning, at least in simple cases.
Binding a temporary to a non-const reference is something that the compiler can easily detect, and so the standard does require a diagnostic for that.