Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can you return a function by reference for a local variable and not for temporary variable? c++

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.

like image 553
AlexDan Avatar asked Mar 06 '12 15:03

AlexDan


People also ask

Why is it unsafe for a function to return a local variable by reference?

The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

Can we return a local variable by reference?

Objects returned by reference must live beyond the scope of the function returning the reference, or a dangling reference will result. Never return a local variable by reference.

Can we return local variable in C?

The problem is, we return address of a local variable which is not advised as local variables may not exist in memory after function call is over. So in simple words, Functions can't return arrays in C. However, inorder to return the array in C by a function, one of the below alternatives can be used.

What is the advantage of returning a reference from the function?

Returning a reference returns by reference. In addition to allowing modification of the returned object, this does not make a copy and saves whatever effort would have been consumed by making a copy.


1 Answers

Returning a reference to a local is something that can be difficult or impossible for the compiler to detect. For example:

int & f()
{
    int x;
    extern int & g(int & x);

    // Does this return a reference to "x"?
    // The compiler has no way to tell.
    return g(x);
}

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.

like image 134
Mike Seymour Avatar answered Nov 14 '22 23:11

Mike Seymour