Why can you return a function by reference for a local variable, and not for a temporary variable? C ++

for example, this function f is defined as follows:

int f(int x){return x;}

as you know, you cannot assign a link to this temporary int:

int& rf=f(2);// this will give an error

but if I redefine my function f as follows:

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 does the compiler not allow you to create a temporary link that will be destroyed after the state (in the first case). and, on the other hand, it allows you to create a f (2) link to x, while the compiler knows that this will be destroyed after return.

+5
source share
6 answers

Returning a link to local is something that may be difficult or impossible for the compiler to detect. For instance:

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);
}

, , , ; , , " " , - , undefined. , , .

- , , .

+7

, , - undefined.

:

int& f(int x)
{
   return x;
}
+1

rvalue , .

const int& rf=f(2); 
+1

, , .

, , , , return , , ( ). .

, , . - , , , . , , , ( , ).

, , , , , . :

struct Foo {
    static void set(Foo &f) { f.val = 0; }
    int val;
    int bar() {
        set(*this);
        return val;
    }
};

std::cout << Foo().bar() << "\n";

Foo() , set(*this) ( , lvalue *this, , ). , . - - - .

+1

, , , , - .

undefined.

since the variable is local, you can be sure that the link is incorrect

0
source

The problem is that semantically there is no difference between a variable on the stack or a variable on the heap, etc. Thus, the language has no choice but to allow this, even if this behavior is undefined. In the first example, you get a slight compilation error because you are trying to bind a link to a temporary variable that may be prohibited by the language.

0
source

All Articles